我正在尝试为地图工具做一个简单的地理编码功能。我很好地获得了地理编码,但我希望将location对象作为地理编码函数的返回值传回。
如下所示:
function codeAddress(address) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var location = results[0].geometry.location;
console.dir(location);
return location;
} else {
return false;
}
});
}location项的console.dir显示了预期的location对象,因此函数正在被调用并成功返回数据。
此函数由另一个进程调用,然后该进程将构建标记。
if (coordinates = codeAddress(myaddress){
// do stuff
}但是,coordinates变量的计算结果始终是未定义的,因此永远不会满足“做东西”的条件。
我知道我可能遗漏了一些关于坐标变量的定义,但我不确定它是什么。
谢谢你的帮助。
http://jsfiddle.net/2TXZ4/3/上的基本代码,不管是什么原因,地图都无法绘制。
发布于 2011-06-22 05:41:01
geocode方法是异步的,因此您需要在提供给该方法的回调中进行任何处理,或者您可以像下面这样的问题/答案描述(How do I return a variable from Google Maps JavaScript geocoder callback?)提供对codeAddress方法的回调。在下面的代码中,我将您在doStuff函数中所做的操作转移到了geocode函数的回调中-它应该可以工作,但我无法使用您提供的jfiddle链接对其进行测试(可能是由于Google Maps API键的原因)。我希望这能帮到你!
function codeAddress(address) {
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var location = results[0].geometry.location;
console.log(location);
map.setCenter(location);
var marker = new google.maps.Marker({
map: map,
position: location
});
} else {
alert("Geocode was not successful for " + address);
}
});
}
window.doStuff = function() {
var address = document.getElementById("address").value;
codeAddress(address);
}发布于 2011-06-22 02:56:08
if (coordinates = codeAddress(myaddress) -这是一种赋值,而不是比较。
好了,这里有一个疯狂的技巧(确实有效):
<script type="text/javascript"> var geocoder; var loc; var l = false;
function initialize() {
geocoder = new google.maps.Geocoder();
var mapDiv = document.getElementById('map_canvas');
map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
}); }
function codeAddress(address) {
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
loc = results[0].geometry.location; l = true;
console.log(loc); //alert (loc);
//return loc; doStuff(loc)
} else {
return false;
}
}); }
function doStuff(geo_marker){ if(l==false){
var thisaddress = document.getElementById("address").value;
var myResult = codeAddress(thisaddress); }else{
if (loc) {
map.setCenter(loc);
var marker = new google.maps.Marker({
map: map,
position: loc
});
l = false; //important to use function more than once :))
} else {
alert("Geocode was not successful");
} }
};
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<body>
<div>
<input id="address" type="textbox" value="Sydney, NSW">
<input type="button" value="Geocode" onclick="window.doStuff()">
</div>
<div id="map_canvas" style="height:600px; width: 500px; position: absolute;
top: 80px"> </div>
</body>我确实认为在一个函数中进行地理编码并将标记添加到地图中更有意义,以避免在函数之间来回调用。
https://stackoverflow.com/questions/6430466
复制相似问题