【问题标题】:unable to calculate the distance betweeen two points in google maps无法计算谷歌地图中两点之间的距离
【发布时间】:2013-09-30 08:40:57
【问题描述】:

我正在做一个需要计算两点之间距离的项目。 我只是使用了距离函数。我只是好奇,当我警觉时,结果是正确的。但是,当我使用 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>

【问题讨论】:

  • 一个快速的谷歌搜索提供了这个页面,movable-type.co.uk/scripts/latlong.html - 它有 Javascript 变量以及如何计算距离和方位的数学。
  • 请详细说明“它不起作用”。什么都没发生?得到意想不到的结果?发生错误?其他? Ähh.. 实际上将您的 p 放在 script 之前。

标签: javascript html api google-maps distance


【解决方案1】:

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

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

该 API 没有 google.maps.LatLng 对象的 distanceFrom 方法。要在 v3 API 中计算两个坐标之间的(直线)距离,请使用 geometry library computeDistanceBetween 方法。

【讨论】:

    猜你喜欢
    • 2010-12-02
    • 1970-01-01
    • 1970-01-01
    • 2011-09-21
    • 2012-04-29
    • 1970-01-01
    • 2016-04-12
    • 2014-07-12
    相关资源
    最近更新 更多