2017-06-02 79 views
-1

我想在我的javascript中实现Google API地图。根据地址,我想获取相应的纬度/经度并在此位置显示地图。当我硬编码的位置,它的作品。当我使用地理编码器的值时,地图是空的。这里是代码:谷歌地图API - 不接受来自地理编码的值

<script> 
    function initMap() { 
     var loc = []; 
     var geocoder = new google.maps.Geocoder(); 
     var address = "New York"; 

     geocoder.geocode({ 'address': address }, function (results, status) { 
      if (status == google.maps.GeocoderStatus.OK) { 
       loc[0] = results[0].geometry.location.lat(); 
       loc[1] = results[0].geometry.location.lng(); 
       alert(loc); 

      } else { 
       alert("Geocode was not successful for the following reason: " + status); 
      } 
     }); 


     // Create a map object and specify the DOM element for display. 
    var map = new google.maps.Map(document.getElementById('map'), { 
     center: { lat: loc[0], lng: loc[1] }, 
     scrollwheel: false, 
     zoom: 8 
    }); 
} 

       </script> 

alert(loc)函数显示正确的纬度和经度值,但地图看起来仍然是空的。任何想法为什么?

回答

0

geocoder.geocode()异步工作。这意味着您应该将映射初始化放入回调函数中。目前您在地理编码回调被触发之前初始化地图。

function initMap() { 
    var map; 
    var loc = []; 
    var geocoder = new google.maps.Geocoder(); 
    var address = "New York"; 

    geocoder.geocode({ 'address': address }, function (results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      loc[0] = results[0].geometry.location.lat(); 
      loc[1] = results[0].geometry.location.lng(); 
      //alert(loc); 

      // Create a map object and specify the DOM element for display. 
      map = new google.maps.Map(document.getElementById('map'), 
       { 
        center: { lat: loc[0], lng: loc[1] }, 
        scrollwheel: false, 
        zoom: 8 
       }); 

     } else { 
      alert("Geocode was not successful for the following reason: " + status); 
     } 
    }); 

希望这会有所帮助!

+0

非常感谢你! – jazy

+0

乐意提供帮助。如果此答案解决了您的问题,请将其标记为已接受。 – xomena