Travel Distance between two Lat and Long

前端 未结 3 471
故里飘歌
故里飘歌 2021-02-06 05:34

I am looking to calculate and give the distance between two sets of Lat and Long for travel on Road.

I have had a look at the Google\'s Directions and Distance Matrix A

相关标签:
3条回答
  • 2021-02-06 06:15

    It give the distance between two locations.

    First you need to get latitude, longitude of source and same for destination. Pass these in this method.

    It return you distance between them.

    public float distanceFrom(float lat1, float lng1, float lat2, float lng2) {
        double earthRadius = 3958.75;
        double dLat = Math.toRadians(lat2-lat1);
        double dLng = Math.toRadians(lng2-lng1);
        double a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.sin(dLng/2) * Math.sin(dLng/2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
        double dist = earthRadius * c;
        int meterConversion = 1609;
        return new Float(dist * meterConversion).floatValue();
    }
    
    0 讨论(0)
  • 2021-02-06 06:26

    If You are looking for driving distance NOT shortest distance then You can try to call API service with URL like:

    http://maps.googleapis.com/maps/api/distancematrix/json?origins=54.406505,18.67708&destinations=54.446251,18.570993&mode=driving&language=en-EN&sensor=false
    

    This will result in JSON like this:

    {
       "destination_addresses" : [ "Powstańców Warszawy 8, Sopot, Polska" ],
       "origin_addresses" : [ "majora Henryka Sucharskiego 69, Gdańsk, Polska" ],
       "rows" : [
          {
             "elements" : [
                {
                   "distance" : {
                      "text" : "24,7 km",
                      "value" : 24653
                   },
                   "duration" : {
                      "text" : "34 min",
                      "value" : 2062
                   },
                   "status" : "OK"
                }
             ]
          }
       ],
       "status" : "OK"
    }
    

    Result distance is actual road distance between two locations.

    You can find more details in The Google Distance Matrix API

    0 讨论(0)
  • 2021-02-06 06:32

    You might want to search a little more before you ask.

    Anyways, use the Haversine formula

    rad = function(x) {return x*Math.PI/180;}
    
    distHaversine = function(p1, p2) {
      var R = 6371; // earth's mean radius in km
      var dLat  = rad(p2.lat() - p1.lat());
      var dLong = rad(p2.lng() - p1.lng());
    
      var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
              Math.cos(rad(p1.lat())) * Math.cos(rad(p2.lat())) * Math.sin(dLong/2) * Math.sin(dLong/2);
      var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
      var dist = R * c;
    
      return dist.toFixed(3);
    }
    
    0 讨论(0)
提交回复
热议问题