如何确定一个纬度/经度对是否落在另一个纬度/经度对的半径内?

问题描述 投票:0回答:2

这是我想弄清楚的一个例子:

  • 设备 A 位于 40.7128 / -74.0060(纬度/经度)

  • 位置 B 位于 40.730610 / -73.935242

  • 半径 = 10 英里

还有问题: 设备 A 是否在位置 B 周围的半径范围内?

我不在乎语言或技术,只想完成工作。我懂一些 Python、JS 和 Java。

有人知道解决这个问题的好/有效的方法吗?

geolocation gis geospatial geo
2个回答
0
投票

我会计算两点之间的距离并检查它是否小于半径。

这个线程给出了一些关于如何在 python 中实现它的想法:根据纬度/经度获取两点之间的距离


0
投票

要确定纬度/经度对是否落在另一对纬度/经度的特定半径内,您可以使用半正弦公式,该公式根据给定的纬度和经度坐标计算地球表面上两点之间的距离。然后,您可以将计算出的距离与半径进行比较,看看它是否在所需的范围内。以下是如何执行此操作的 Java 示例:

import java.lang.Math;

public class LocationDistanceCalculator {

    public static void main(String[] args) {
        // Coordinates for Device A (40.7128, -74.0060)
        double latA = 40.7128;
        double lonA = -74.0060;

        // Coordinates for Location B (40.730610, -73.935242)
        double latB = 40.730610;
        double lonB = -73.935242;

        // Radius in miles
        double radius = 10.0;

        // Check if Device A is within the radius of Location B
        boolean isWithinRadius = isWithinRadius(latA, lonA, latB, lonB, radius);

        if (isWithinRadius) {
            System.out.println("Device A is within the radius of Location B.");
        } else {
            System.out.println("Device A is not within the radius of Location B.");
        }
    }

    // Calculate the distance between two latitude/longitude points using the Haversine formula
    public static double calculateDistance(double lat1, double lon1, double lat2, double lon2) {
        final int R = 6371; // Radius of the Earth in kilometers

        double lat1Rad = Math.toRadians(lat1);
        double lat2Rad = Math.toRadians(lat2);

        double deltaLat = Math.toRadians(lat2 - lat1);
        double deltaLon = Math.toRadians(lon2 - lon1);

        double a = Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2) +
                   Math.cos(lat1Rad) * Math.cos(lat2Rad) *
                   Math.sin(deltaLon / 2) * Math.sin(deltaLon / 2);

        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

        double distance = R * c; // Distance in kilometers

        // Convert the distance to miles
        return distance * 0.621371;
    }

    // Check if a point is within a certain radius of another point
    public static boolean isWithinRadius(double lat1, double lon1, double lat2, double lon2, double radius) {
        double distance = calculateDistance(lat1, lon1, lat2, lon2);
        return distance <= radius;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.