2013-09-24 48 views
0

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

一个快速的Google搜索提供了这个页面,http://www.movable-type.co.uk/scripts/latlong.html - 它具有JavaScript变量和数学背后的如何计算距离和方位。 – Enijar

+1

请详细说明“它不起作用”。什么都没发生?获得意外的结果?发生错误?其他? Ähh..实际上把'p'放在'script'前面。 – Teemu

回答

0

你的脚本,包括谷歌地图JavaScript API V3:

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

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

+0

非常感谢,非常感谢! – user2804616