Get the distance between two geo points

后端 未结 9 594
旧巷少年郎
旧巷少年郎 2020-11-27 09:11

I want to make an app which checks the nearest place where a user is. I can easily get the location of the user and I have already a list of places with latitude and longitu

9条回答
  •  一整个雨季
    2020-11-27 10:02

    An approximated solution (based on an equirectangular projection), much faster (it requires only 1 trig and 1 square root).

    This approximation is relevant if your points are not too far apart. It will always over-estimate compared to the real haversine distance. For example it will add no more than 0.05382 % to the real distance if the delta latitude or longitude between your two points does not exceed 4 decimal degrees.

    The standard formula (Haversine) is the exact one (that is, it works for any couple of longitude/latitude on earth) but is much slower as it needs 7 trigonometric and 2 square roots. If your couple of points are not too far apart, and absolute precision is not paramount, you can use this approximate version (Equirectangular), which is much faster as it uses only one trigonometric and one square root.

    // Approximate Equirectangular -- works if (lat1,lon1) ~ (lat2,lon2)
    int R = 6371; // km
    double x = (lon2 - lon1) * Math.cos((lat1 + lat2) / 2);
    double y = (lat2 - lat1);
    double distance = Math.sqrt(x * x + y * y) * R;
    

    You can optimize this further by either:

    1. Removing the square root if you simply compare the distance to another (in that case compare both squared distance);
    2. Factoring-out the cosine if you compute the distance from one master point to many others (in that case you do the equirectangular projection centered on the master point, so you can compute the cosine once for all comparisons).

    For more info see: http://www.movable-type.co.uk/scripts/latlong.html

    There is a nice reference implementation of the Haversine formula in several languages at: http://www.codecodex.com/wiki/Calculate_Distance_Between_Two_Points_on_a_Globe

提交回复
热议问题