Fastest Way to Find Distance Between Two Lat/Long Points

后端 未结 15 964
时光说笑
时光说笑 2020-11-21 10:12

I currently have just under a million locations in a mysql database all with longitude and latitude information.

I am trying to find the distance between one point a

15条回答
  •  天涯浪人
    2020-11-21 10:35

    A fast, simple and accurate (for smaller distances) approximation can be done with a spherical projection. At least in my routing algorithm I get a 20% boost compared to the correct calculation. In Java code it looks like:

    public double approxDistKm(double fromLat, double fromLon, double toLat, double toLon) {
        double dLat = Math.toRadians(toLat - fromLat);
        double dLon = Math.toRadians(toLon - fromLon);
        double tmp = Math.cos(Math.toRadians((fromLat + toLat) / 2)) * dLon;
        double d = dLat * dLat + tmp * tmp;
        return R * Math.sqrt(d);
    }
    

    Not sure about MySQL (sorry!).

    Be sure you know about the limitation (the third param of assertEquals means the accuracy in kilometers):

        float lat = 24.235f;
        float lon = 47.234f;
        CalcDistance dist = new CalcDistance();
        double res = 15.051;
        assertEquals(res, dist.calcDistKm(lat, lon, lat - 0.1, lon + 0.1), 1e-3);
        assertEquals(res, dist.approxDistKm(lat, lon, lat - 0.1, lon + 0.1), 1e-3);
    
        res = 150.748;
        assertEquals(res, dist.calcDistKm(lat, lon, lat - 1, lon + 1), 1e-3);
        assertEquals(res, dist.approxDistKm(lat, lon, lat - 1, lon + 1), 1e-2);
    
        res = 1527.919;
        assertEquals(res, dist.calcDistKm(lat, lon, lat - 10, lon + 10), 1e-3);
        assertEquals(res, dist.approxDistKm(lat, lon, lat - 10, lon + 10), 10);
    

提交回复
热议问题