【发布时间】: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