Calculate distance between two points in google maps V3

后端 未结 15 1724
醉梦人生
醉梦人生 2020-11-22 02:27

How do you calculate the distance between two markers in Google maps V3? (Similar to the distanceFrom function inV2.)

Thanks..

15条回答
  •  失恋的感觉
    2020-11-22 03:02

    Just add this to the beginning of your JavaScript code:

    google.maps.LatLng.prototype.distanceFrom = function(latlng) {
      var lat = [this.lat(), latlng.lat()]
      var lng = [this.lng(), latlng.lng()]
      var R = 6378137;
      var dLat = (lat[1]-lat[0]) * Math.PI / 180;
      var dLng = (lng[1]-lng[0]) * Math.PI / 180;
      var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
      Math.cos(lat[0] * Math.PI / 180 ) * Math.cos(lat[1] * Math.PI / 180 ) *
      Math.sin(dLng/2) * Math.sin(dLng/2);
      var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
      var d = R * c;
      return Math.round(d);
    }
    

    and then use the function like this:

    var loc1 = new GLatLng(52.5773139, 1.3712427);
    var loc2 = new GLatLng(52.4788314, 1.7577444);
    var dist = loc2.distanceFrom(loc1);
    alert(dist/1000);
    

提交回复
热议问题