我一直在尝试将地址地理编码为 LatLng 坐标,但这样做有很多困难。我知道geocode()
是一个异步函数,我一直在玩弄回调无济于事。我一直在看类似这样的其他帖子(如何从异步回调函数返回值?),但我很难理解这个概念。如果有人能告诉我如何正确地执行该回调函数,将不胜感激。很头疼这个。能够让回调执行alert()
提供正确 LatLng 的操作,但未设置位置参数。抱歉,无法从前面引用的示例中弄清楚。语言很新。您可以指出我理解这个概念的任何参考资料也非常感谢。谢谢!
var location;
var image;
var map;
var geocoder;
var address;
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(42.763146, -73.3776),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
var cloudLayer = new google.maps.weather.CloudLayer();
cloudLayer.setMap(map);
addressSet(function(address) {
console.log(address);
// tried to set location = address;, location = new google.maps.LatLng(address);
// neither works
});
addMtsToMap(location,
map,
new google.maps.MarkerImage("img/mts/skier.png", null, null, null, new google.maps.Size(50,50)));
}
function addMtsToMap(location, map, image) {
var marker = new google.maps.Marker({
position: location,
map: map,
icon: image
});
var infoWindow = new google.maps.InfoWindow({content: "<h1>Powder!!!</h1>"});
google.maps.event.addListener(marker, "click", function() {
infoWindow.open(map, marker);
});
}
function addressSet(callback) {
geocoder = new google.maps.Geocoder();
geocoder.geocode({address: "Killington+VT"}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
address = results[0].geometry.location;
callback(address);
}
});
}