将google地理编码返回的值存储在外部javascript变量中
无法将谷歌地理编码返回的值存储到全局/外部(javascript)变量中(在以下情况下为latlng1)。。。。也许是因为变量在地理编码完成之前就得到了它的值 对于以下代码中的:将google地理编码返回的值存储在外部javascript变量中,javascript,jquery,google-maps,google-maps-api-3,return,Javascript,Jquery,Google Maps,Google Maps Api 3,Return,无法将谷歌地理编码返回的值存储到全局/外部(javascript)变量中(在以下情况下为latlng1)。。。。也许是因为变量在地理编码完成之前就得到了它的值 对于以下代码中的: alert(('latlon='+latlng1); //shows undefined 但是, 那么,如何等待地理编码返回非空值,然后再将其分配给变量 这能解决问题吗?或者代码中还有其他缺陷吗 然而,除此之外,本规范的所有部分都可以正常工作(如下文规范中的注释所述);我看到标记也被正确地放置在地图上 这是我的密码:
alert(('latlon='+latlng1); //shows undefined
但是,
那么,如何等待地理编码返回非空值,然后再将其分配给变量
这能解决问题吗?或者代码中还有其他缺陷吗
然而,除此之外,本规范的所有部分都可以正常工作(如下文规范中的注释所述);我看到标记也被正确地放置在地图上
这是我的密码:-
<script src="path_to_javascript_file.js"></script>
$(some_element).click(function() {
var input = document.getElementById(some_input_element).vlaue ;
var get_geocodes = function get_value(latLng) {
alert('got value = '+latLng); //gives the coorect value
if (latLng == null){
geocode(input, get_geocodes)}
return latLng;
}
latlng1 = geocode(input, get_geocodes);
alert('latlon='+latlng1); //says undefined
正如评论中提到的,您需要等待google.maps.Geocoder()完成其执行 您的函数geocode不会返回任何内容,因此变量latlng1未定义也就不足为奇了。无论如何,如果geocode将返回latlng1值,您无法保证latlng1将被定义 我的建议是:
latlng1 = results[0].geometry.location;
地理编码是异步的。如果您需要“等待”值可用,可以通过在回调函数中处理它来实现。对不起,这是我在这里犯的一个键入错误,我现在已经更正了…它的
。值在原始代码中
。@geocodezip我还需要向我的回调函数(代码中提到)添加什么??您提供的链接没有帮助……但不是get\u value()
函数(存储在var get\u geocodes
中,并作为mycallback
传递给geocode()
函数),返回latLng
值,正如这里调用的那样:if(status==google.maps.GeocoderStatus.OK&&results.length):mycallback(latLng);
?不,它不是那样工作的。您需要专门为geocode()函数添加return语句。只有在goecode()之后将返回一些值。也无法将其直接分配给全局变量…因为我需要根据传入的请求在不同的变量中存储多个值…好的..可以这样做--a_函数(args){return b_函数(args)}
,其中b_函数是--b_函数(args){return some_值;}
,这样一个var result=a_函数(arg1);
从b_函数中获取返回值
,
?已解决!…直接将该值分配给一个全局声明的javascript对象……并修改geocode(query)
函数以包含一个附加参数geocode(query,key)
让函数知道需要修改对象中哪个键的值(存储结果)…谢谢讨论:)
function geocode(query, mycallback) {
var geocoder = new google.maps.Geocoder();
latLng = null
geocoder.geocode( { 'address': query},
function callback(results, status) {
if (status == google.maps.GeocoderStatus.OK && results.length) {
var latLng = results[0].geometry.location;
console.log('geocoding successful : ' + latLng); //gives the correct value
add_marker(latLng, query);
mycallback(latLng);
}
else {
console.log("geocoding unsuccessful because of: " + status);
}
});
}
function add_marker(latLng , query) {
var new_marker = new google.maps.Marker({
position: new google.maps.LatLng(latLng.lat(), latLng.lng()),
map: map,
title: query ,
animation: google.maps.Animation.DROP
});
console.log(new_marker.getPosition().lat()); //gives the correct value
console.log(mew_marker.getPosition().lng()); //gives the correct value
alert('added_marker'+latLng+',,'+location); //gives the correct value
}
latlng1 = results[0].geometry.location;