Travel Distance between two Lat and Long

前端 未结 3 473
故里飘歌
故里飘歌 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: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);
    }
    

提交回复
热议问题