分享一个关于java计算经纬度距离的工具类

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Location {
	private double latitude;
	private double longitude;

	public double getLatitude() {
		return latitude;
	}

	public double getLongitude() {
		return longitude;
	}

	public static boolean isWithinRadius(Location target, List<Location> locations, double radius) {
		for (Location location : locations) {
			double distance = haversineDistance(target, location);
			if (distance <= radius) {
				return true;
			}
		}
		return false;
	}

	private static double haversineDistance(Location loc1, Location loc2) {
		final int R = 6371; // 地球半径,单位:千米
		double lat1 = Math.toRadians(loc1.getLatitude());
		double lon1 = Math.toRadians(loc1.getLongitude());
		double lat2 = Math.toRadians(loc2.getLatitude());
		double lon2 = Math.toRadians(loc2.getLongitude());

		double dLat = lat2 - lat1;
		double dLon = lon2 - lon1;

		double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
				+ Math.cos(lat1) * Math.cos(lat2) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
		double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

		return R * c * 1000; // 转换为米
	}

	/**
	 * Object 转集合
	 *
	 * @param obj
	 * @return
	 */
	public static List<Location> convertObjectToListOfMaps(Object obj) {
		List<Location> listOfMaps = new ArrayList<>();
		if (obj instanceof List) {
			List<?> list = (List<?>) obj;
			for (Object item : list) {
				if (item instanceof Map) {
					Map<String, String> item_ = (Map<String, String>) item;
					listOfMaps.add(
							new Location(Double.parseDouble(item_.get("lat")), Double.parseDouble(item_.get("lon"))));
				}
			}
		}
		return listOfMaps;
	}
}

在这里插入图片描述
注解为lombok注解,此处大致意思为getset方法 全参和无参构造方法【知道的请忽略】 具体用法请自行百度

你可能感兴趣的:(工具类,随笔,java,开发语言)