谷歌地图computeDistanceBetween()返回NaN没有拼写错误

时间:2018-03-15 00:27:34

标签: javascript google-maps-api-3 google-geocoding-api

我在下面有这个代码,我试图执行computeDistanceBetween函数,但它返回NaN。没有拼写错误。我真的不知道它发生了什么。请帮忙!



<html>
<head></head>
<body>
<div id ="VP"><button onClick="getAddressFromCoord('Port-Louis')">1</button>
</div>
<div id ="VP"><button onClick="findNearestEmpl()">2</button></div>
<script>
	var emplcoordinates= [];
	var empDistance=[];
       function getAddressFromCoord(Address){
	   var coordinate;
	
	   geocoder = new google.maps.Geocoder();
	   var address = 'port louis';
       geocoder.geocode({
       'address': address
    }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
           coordinate = results[0].geometry.location.lat()+','+results[0].geometry.location.lng();
		   emplcoordinates.push(new google.maps.LatLng(coordinate));
		   console.log(emplcoordinates);
        } else {
            coordinate = 0;
			emplcoordinates.push(new google.maps.LatLng(coordinate));
			console.log(emplcoordinates);
        }
    });
	
}

function findNearestEmpl(){
	var checkpoint = new google.maps.LatLng(-20.244299955429746,57.459360252793886);
	for(i=0;i<emplcoordinates.length;i++)
	{
		empDistance.push( google.maps.geometry.spherical.computeDistanceBetween(checkpoint,emplcoordinates[i]));
		console.log('distance1 ='+empDistance[i])
	}
	
}
</script>

</body>
</html>
&#13;
&#13;
&#13;

按钮1然后按钮2

1 个答案:

答案 0 :(得分:1)

似乎将纬度和经度转换为如下所示的字符串不起作用:

coordinate = results[0].geometry.location.lat()+','+results[0].geometry.location.lng();
emplcoordinates.push(new google.maps.LatLng(coordinate));

然而,这对我有用:

emplcoordinates.push(new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng()));

更简单,如果没有特别的理由创建一个单独的新LatLng对象:

emplcoordinates.push(results[0].geometry.location);

我得到的输出是:

distance1 =10263.42066184296