2017-06-02 77 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