google maps 計算距離
方法一:
計算距離
方法二:
- var marker1 = new google.maps.Marker({
- position: new google.maps.LatLng("31.95678", "177.898673"),
- map: map,
- title:"old"
- });
- var marker2 = new google.maps.Marker({
- position: new google.maps.LatLng("31.45678", "177.098673"),
- map: map,
- title:"new"
- });
計算距離
- var meters = google.maps.geometry.spherical.computeDistanceBetween(marker1.getPosition(), marker2.getPosition());
- document.getElementById("distance").innerText = meters+"公尺";
- 方法说明:computeDistanceBetween(from:LatLng, to:LatLng, radius?:number) 公尺 。
方法二:
- var EARTH_RADIUS = 6371;//地球半徑6371km
- function rad(d)
- {
- return d * Math.PI/ 180.0;
- }
- function getDistance(lat1, lng1, lat2, lng2)
- {
- var radLat1 = rad(lat1);
- var radLat2 = rad(lat2);
- var a = radLat1 - radLat2;
- var b = rad(lng1) - rad(lng2);
- var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
- Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
- s = s * EARTH_RADIUS;
- s = Math.round(s * 10000) / 10000;
- return s;
- }
- var distance = getDistance(marker1.getPosition().lat(), marker1.getPosition().lng(), marker2.getPosition().lat(), marker2.getPosition().lng());
留言