2017-06-02 12 views
-1

JavaScript APIでGoogle APIマップを実装しようとしています。住所に基づいて、私は対応する緯度/経度を取得し、この場所に地図を表示したいと思います。私は場所をハードコードするとき、それは動作します。ジオコーダーからの値を使用すると、マップは空です。ここでコードである:Google Maps 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> 

アラート(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

関連する問題