簡體   English   中英

無法計算谷歌地圖中兩個點之間的距離

[英]unable to calculate the distance betweeen two points in google maps

我正在做一個需要計算兩點之間距離的項目。 我只是使用distancefrom函數。 我很謹慎,當我發出警報時,結果是正確的。 但是,當我使用document.getElementById時,它不起作用。 我想知道這里是否有人可以幫助我弄清楚代碼中發生了什么……非常感謝!

<html>
<head>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script>
    google.maps.LatLng.prototype.distanceFrom = function(newLatLng) {
        if (newLatLng==undefined) return false;

        var dLat = (newLatLng.lat()-this.lat()) * Math.PI / 180;
        var dLon = (newLatLng.lng()-this.lng()) * Math.PI / 180;
        var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(this.lat() * Math.PI / 180 ) * Math.cos(newLatLng.lat() * Math.PI / 180 )* Math.sin(dLon/2) * Math.sin(dLon/2);
        return 6371000 * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
      }

</script>
</head>
<body>
<script>
var loc1 = new google.maps.LatLng(52.5773139, 1.3712427);
var loc2 = new google.maps.LatLng(52.4788314, 1.7577444);
alert (Math.round(loc1.distanceFrom(loc2)/10)/160 + 'mi');
document.getElementById("1").innerHTML=Math.round(loc1.distanceFrom(loc2)/10)/160 + 'mi';
</script>
        <p id="1">xyz
        </p>


        </body>
</html>

您的腳本包含Google Maps Javascript API v3:

<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>

該API沒有google.maps.LatLng對象的distanceFrom方法。 要在v3 API中計算兩個坐標之間的(直線)距離,請使用幾何圖形庫 computeDistanceBetween方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM