gpt4 book ai didi

javascript - Google map API v3 - 地理编码

转载 作者:行者123 更新时间:2023-11-28 02:18:49 25 4
gpt4 key购买 nike

我想要一张有 2 个标记的 map 。如果我使用 LatLng(参见 JS 代码/工作正常/),那没问题...但是一旦我尝试使用地理编码(参见 JS 代码/你不工作?/) 它不起作用。我想这都是错误的:

var adresse3=geocoder.geocode({'address': 'Winkelriedstrasse 47, 6004 Luzern'})[0].geometry.location;

谁能帮帮我。预先感谢您。

var myCenter=new google.maps.LatLng(47.050944,8.309441);
var geocoder;
var map;
function initialize(){
var mapProp = {
center :myCenter
};
var geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
/*WORKS JUST FINE*/
var marker1=new google.maps.Marker({
position: new google.maps.LatLng(47.050944,8.309441)
});
marker1.setMap(map);
var infowindow1 = new google.maps.InfoWindow({
content:"marker1"
});
google.maps.event.addListener(marker1, 'click', function() {
infowindow1.open(map,marker1);
});
/*Y U NOT WORKING?*/
var adresse3=geocoder.geocode({'address': 'Winkelriedstrasse 47, 6004 Luzern'})[0].geometry.location;
var marker3=new google.maps.Marker({
position: adresse3
});
marker3.setMap(map);
var infowindow3 = new google.maps.InfoWindow({
content:"marker3"
});
google.maps.event.addListener(marker3, 'click', function() {
infowindow3.open(map,marker3);
});
}
google.maps.event.addDomListener(window, 'load', initialize);

最佳答案

您的问题是 geocoder.geocode 是异步的,因此您必须传递 callback function .

改编自Google Maps Documentation :

geocoder.geocode({'address': 'Winkelriedstrasse 47, 6004 Luzern'}, function(results, status)     {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});

关于javascript - Google map API v3 - 地理编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15974336/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com