Javascript 谷歌地图-lat和long或邮政编码
我有下面的代码根据一系列位置在谷歌地图上显示标记,但是我混合了邮政编码和Lat/long,我使用地理编码器将邮政编码转换为Lat/long,但在尝试设置标记时无法使用它们 谢谢你的帮助Javascript 谷歌地图-lat和long或邮政编码,javascript,google-maps,Javascript,Google Maps,我有下面的代码根据一系列位置在谷歌地图上显示标记,但是我混合了邮政编码和Lat/long,我使用地理编码器将邮政编码转换为Lat/long,但在尝试设置标记时无法使用它们 谢谢你的帮助 var geocoder; var map; var pos; var geoLat; var geoLong; var markers = []; var bounds = new google.maps.LatLngBounds(); var locations = [
var geocoder;
var map;
var pos;
var geoLat;
var geoLong;
var markers = [];
var bounds = new google.maps.LatLngBounds();
var locations = [
[null, 'London Eye, London', 51.503454,-0.119562, 4]
,[null, 'Palace of Westminster, London', 51.499633,-0.124755]
,[null, 'The London Dungeon', 'SE1 7PB', , 2] //Value with Postcode
];
function isNumber(o) { return ! isNaN (o-0) && o !== null && o !== "" && o !== false; }
function init() {
geocoder = new google.maps.Geocoder();
var num_markers = locations.length;
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 10,
center: new google.maps.LatLng(locations[0][2], locations[0][3]),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
for (var i = 0; i < num_markers; i++) {
if (isNumber (locations[i][2]) && isNumber (locations[i][3])){
geoLat = locations[i][2]
geoLng = locations[i][3]
alert(typeof(geoLat) +' '+typeof(geoLng)) //generates a correct number number response
}else{
geocoder.geocode( { 'address': locations[i][2]}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
geoLat = results[0].geometry.location.lat()
geoLng = results[0].geometry.location.lng()
alert(typeof(geoLat) +' '+typeof(geoLng)) //generates a correct number number response
}
});
}
pos = new google.maps.LatLng(geoLat, geoLng); // Doesn't get value if a geocodes postcode added in
bounds.extend(pos);
map.fitBounds(bounds);
markers[i] = new google.maps.Marker({
position: pos,
map: map,
id: i,
title: locations[i][1]
});
}
}
google.maps.event.addDomListener(window, 'load', init);
Geolocation请求是一个异步调用,这意味着您的脚本正在运行,而API请求尚未完成。 因此,您有两种选择 直接在回调函数中定义标记
if (status == google.maps.GeocoderStatus.OK) { }
或者编写一个setMarker函数,并在回调函数中调用它
function setMarker(lat, lng){}
一般来说,将地理编码请求作为一项功能也是一种良好的做法,如:
doGeocode: function (address, postal_code, callback) {
console.log("TEST: " + address.toString());
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address,
'componentRestrictions': {
'postalCode': postal_code,
'country': 'de'
}
}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
console.log(results);
callback(results);
} else {
//Error handling
alert('Geocode was not successful for the following reason: ' + status);
}
});
如果你现在想打电话,就这么做吧
doGeocode (adress, postal_code, function (response){
//do your stuff
)};
当geocoder回调触发时,您需要设置位置-这不会立即发生。谢谢@Piskvor-我该怎么做?什么时候点火…谢谢@IntercoolerTurbo-工作得很好。不过,这只是一个一般性的问题,我不明白如果一个值可以在警报中显示,为什么在这一点之后它就不能用于代码?