将google地理编码返回的值存储在外部javascript变量中

storing returned value from google geocoding in an external javascript variable

本文关键字:存储 外部 javascript 变量 google 编码 返回      更新时间:2023-09-26

无法将谷歌地理编码返回的值存储到全局/外部(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会被定义。

我的建议:

  1. 只需调用地理编码器函数,而不将其分配给latlng1
  2. 通过在所有函数之外初始化latlng1变量,使其成为全局变量
  3. 根本不要使用latLng变量,只需将所需值直接分配给全局变量platlng1,如下所示:

    latlng1 = results[0].geometry.location;
    
  4. 在以下两个调用中,将latLng变量替换为platlng1:add_marker(latlng1,query)和mycallback。