将google地理编码返回的值存储在外部javascript变量中
storing returned value from google geocoding in an external javascript variable
无法将谷歌地理编码返回的值存储到全局/外部(javascript)变量(latlng1,在以下情况下)。。。。也许是因为变量在地理编码完成之前就得到了它的值。。。
对于以下代码:
alert(('latlon='+latlng1); //shows undefined
但是,
alert('got value = '+latLng); //gives the coorect value
那么,如何等待地理编码返回一个非null值,然后再将其分配给变量呢??
这能解决问题吗?或者代码中还有其他缺陷吗??
除此之外,代码的所有部分都可以正常工作(如下面代码中的注释所述);我看到标记也被正确地放置在地图上;
这是我的代码:-
<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
下面是我的javascript_file.js(包含在上面代码的开头):
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
}
如注释中所述,您需要等待google.maps.Geocode()完成执行。
您的函数geocode不返回任何内容,因此不会意外地发现变量latlng1理代码将返回latLng值,则不能保证latlng1会被定义。
我的建议:
- 只需调用地理编码器函数,而不将其分配给latlng1
- 通过在所有函数之外初始化latlng1变量,使其成为全局变量
-
根本不要使用latLng变量,只需将所需值直接分配给全局变量platlng1,如下所示:
latlng1 = results[0].geometry.location;
-
在以下两个调用中,将latLng变量替换为platlng1:add_marker(latlng1,query)和mycallback。
相关文章:
- 调整窗口大小时,可拖动的对象会出现在容器外部
- 存储$http如何从$http函数(Angularjs)外部获取可访问变量中的响应
- 将Firebase url存储在外部属性文件中
- 如何在外部文件中存储谷歌地图选项
- 在外部JSON文件中存储对象数组
- 将数据从外部 Javascript 添加到存储
- 如何在外部存储javascript变量(没有服务器)的值
- 从外部域 javascript 保存的本地存储不会保存在外部域下
- 如何将计数器存储在外部文件中并在jquery中加载它
- 如何使用外部存储呈现数据视图的 tpl
- 如何查询外部域,将其存储在chrome扩展中,并调用它在popup.html中显示
- 将外部页面源存储在Javascript变量中
- 将google地理编码返回的值存储在外部javascript变量中
- 哪里是外部js文件在html存储?我可以
- METEOR:从外部api存储数据失败
- 将CSS属性的值作为变量存储在外部配置文件中
- 将外部php样式表的内容存储在html中
- 是否可以在应用外部修改本地存储值
- 如何访问存储在项目外部的javascript文件
- 从外部json文件中获取对象数组,并将其存储在javascript中