jQuery技术:在外部javascript变量中存储谷歌地理编码的返回值

无法将谷歌地理编码的返回值存储到全局/外部(javascript)变量( latlng1 ,在下列情况下)….也许是因为变量在地理编码完成之前获取其值…

对于下面的代码:

alert(('latlon='+latlng1); //shows undefined 

但,

 alert('got value = '+latLng); //gives the coorect value 

那么,如何在将变量分配给变量之前等待地理编码返回非空值?

这会解决问题吗? 或者代码中还有其他缺陷吗?

除此之外,代码的所有部分都可以正常工作(如下面的代码中的注释所述); 我看到标记也正确地放在地图上;

这是我的代码: –

   $(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.Geocoder()完成其执行。

    您的函数地理编码不会返回任何内容,因此不要认为变量latlng1未定义。 无论如何,如果地理编码将返回latLng值,则无法保证将定义latlng1

    我的建议:

      以上就是jQuery教程分享在外部javascript变量中存储谷歌地理编码的返回值相关内容,想了解更多jQuery开发(异常处理)及jQuery教程关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/jquerytutorial/532440.html

      (0)
      上一篇 2020年12月21日
      下一篇 2020年12月21日

      精彩推荐