java实现 给定一个地址经纬度,一组地址经纬度,找出在范围内的地址,和最接近的地址(单位:米)
package com.example.demo10; import java.util.ArrayList; import java.util.List; /** * java实现 给定一个地址经纬度,一组地址经纬度,找出在范围内的地址,和最接近的地址 * * @author longlinji * @date 2024/4/15 */ public class GeoUtils { // 地球半径,单位为公里 // private static final double EARTH_RADIUS = 6371.0; // 地球半径,单位为米 private static final double EARTH_RADIUS_IN_METERS = 6371000.0; // 使用哈弗辛公式计算两点之间的距离 public static double haversineDistance(double lat1, double lon1, double lat2, double lon2) { double dLat = Math.toRadians(lat2 - lat1); double dLon = Math.toRadians(lon2 - lon1); lat1 = Math.toRadians(lat1); lat2 = Math.toRadians(lat2); double a = Math.pow(Math.sin(dLat / 2), 2) + Math.pow(Math.sin(dLon / 2), 2) * Math.cos(lat1) * Math.cos(lat2); double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); return EARTH_RADIUS_IN_METERS * c; } public static void findAddressesWithinRadius(double baseLat, double baseLon, List<double[]> targetCoords, double radius) { List<double[]> withinRadius = new ArrayList<>(); double[] closestPoint = null; double minDistance = Double.MAX_VALUE; for (double[] coords : targetCoords) { double distance = haversineDistance(baseLat, baseLon, coords[1], coords[0]); if (distance <= radius) withinRadius.add(coords); if (distance < minDistance) { minDistance = distance; closestPoint = coords; } } System.out.println("Locations within " + radius + " km radius: "); for (double[] coords : withinRadius) System.out.println("Lon: " + coords[0] + ", Lat: " + coords[1]); if (closestPoint != null && withinRadius.size() > 0) System.out.println("Closest location is at Lon: " + closestPoint[0] + ", Lat: " + closestPoint[1]); } }