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;

    // 使用哈弗辛公式计算两点之间的距离
    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 * 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[0], coords[1]);

            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("Lat: " + coords[0] + ", Lon: " + coords[1]);

        if (closestPoint != null)
            System.out.println("Closest location is at Lat: " + closestPoint[0] + ", Lon: " + closestPoint[1]);
    }

    public static void main(String[] args) {
        double baseLat = 52.5200; // 例如柏林的经纬度
        double baseLon = 13.4050;

        // 一组经纬度坐标点
        List<double[]> targetCoords = new ArrayList<>();
        targetCoords.add(new double[]{52.5201, 13.4051}); // 非常接近的点
        targetCoords.add(new double[]{48.8566, 2.3522});  // 巴黎
        targetCoords.add(new double[]{51.5074, -0.1278}); // 伦敦

        double radius = 500.0; // 500公里范围内

        findAddressesWithinRadius(baseLat, baseLon, targetCoords, radius);
    }
}

 

posted on 2024-04-15 21:33  longlinji  阅读(11)  评论(0编辑  收藏  举报