我正在使用Google Maps Geocoder来获取地址的纬度和经度。然后,我要获取该地址并使用Leaflet,然后将 map 平移到纬度+经度坐标。但是,我从Firebug收到一条错误消息,说Error: Invalid LatLng object: (-33.8674869, 151.20699020000006, undefined)
。我知道我的变量geolocation
返回-33.8674869, 151.20699020000006
,但未返回未定义的。是什么原因引起的?
<body onload="initialize()">
<div id="result"></div>
<div>
<input id="address" type="textbox" value="Sydney, NSW">
<input type="button" value="Geocode" onclick="codeAddress()">
</div>
<div id="map"></div>
<script type="text/javascript">
var map = L.map('map').setView([33.7489954, -84.3879824], 13);
var geocoder;
function initialize() {
geocoder = new google.maps.Geocoder();
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var geolocation = String(results[0].geometry.location);
var geolocation = geolocation.replace('(','');
var geolocation = geolocation.replace(')','');
map.panTo([geolocation]);
} else {
$('#result').html('Geocode was not successful for the following reason: ' + status);
}
});
};
L.tileLayer('http://{s}.tile.cloudmade.com/apikeyputhere/997/256/{z}/{x}/{y}.png', {
maxZoom: 18
}).addTo(map);
</script>
最佳答案
替换为:
var geolocation = String(results[0].geometry.location);
var geolocation = geolocation.replace('(','');
var geolocation = geolocation.replace(')','');
map.panTo([geolocation]);
接着就,随即:
map.panTo([results[0].geometry.location.lat(),results[0].geometry.location.lng()]);
说明:
您为第一个数组值分配一个字符串,它与以下内容相同:
geolocation=new Array('-33.8674869, 151.20699020000006')//contains 1 string
该字符串将不被求值,它将保留为1个字符串,但是您需要一个具有2个浮点数的数组:
geolocation=new Array(-33.8674869, 151.20699020000006)//contains 2 floats
undefined
是提供给panTo()
的数组中缺少的第二项关于javascript - 合并Google Maps Geocoder和Leaflet Map接收错误:无效的LatLng对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12773542/