2016-08-12 7 views
0

私の住所を経度と緯度に変換するためにgoogle maps apiを使用しようとしています。住所を緯度と経度に変換してからページに地図を表示する方法

PHPから/ Laravelを使用してDBからアドレスを取得するのにちょっと注意してください。だから、ニューヨークのハードコーディングされた価値は、私はこの仕事を得た後に動的になります。

Htmlの

<div id="map" style="height:250px"></div> 

Javascriptを私はエラーになってる瞬間

<script> 

    var geocoder = new google.maps.Geocoder(); 
    var address = "new york"; 

    geocoder.geocode({ 'address': address}, function(results, status) { 

     if (status == google.maps.GeocoderStatus.OK) { 
      var latitude = results[0].geometry.location.lat(); 
      var longitude = results[0].geometry.location.lng(); 
      alert(latitude); 
     } 
    }); 

    function initMap() { 
     var myLatLng = {lat: latitude, lng: longitude}; 

     var map = new google.maps.Map(document.getElementById('map'), { 
      zoom: 4, 
      center: myLatLng 
     }); 

     var marker = new google.maps.Marker({ 
      position: myLatLng, 
      map: map, 
      title: 'Hello World!' 
     }); 
    } 




</script> 

<script async defer 
     src="https://maps.googleapis.com/maps/api/js?key=keyremoved&callback=initMap"> 
</script> 

"捕捉されないにReferenceErrorを:Googleが定義されていません"

+0

あなたは 'initMap'が呼び出される前に、あなたのコードの上半分を実行している - 「' initMap'、あなたの内側 'initMap'の上にあるコードを置く - GoogleマップのAPIがロードされるとinitMapが呼び出されますあなたの目標達成に近づくでしょう。 –

+0

'initMap'関数内でジオコーダーコードを動かしてください。マップjs URIのURLにコールバック関数があります。これは、マップスクリプトがロードされると実行されます。スクリプトが –

+0

の[Google Maps APIで緯度と経度の代わりに住所を使用する]をロードする前に、新しい 'google.maps.Geocoder();'を呼び出しています(http://stackoverflow.com/questions/15925980/using -address-instead-of-longitude-and-latitude-google-maps-api) – geocodezip

答えて

1

上記のように、コードは自分のコールバック関数の中に入れる必要がありました。

<script>  
     function initMap(address) { 

      var geocoder = new google.maps.Geocoder(); 

      geocoder.geocode({ 'address': address}, function(results, status) { 

       if (status == google.maps.GeocoderStatus.OK) { 
        var latitude = results[0].geometry.location.lat(); 
        var longitude = results[0].geometry.location.lng(); 
       } 

       console.log(latitude); 
       console.log(longitude); 

       var myLatLng = {lat: latitude, lng: longitude}; 

       var map = new google.maps.Map(document.getElementById('map'), { 
        zoom: 4, 
        center: myLatLng 
       }); 

       var marker = new google.maps.Marker({ 
        position: myLatLng, 
        map: map, 
        title: 'Hello World!' 
       }); 

      }); 


     } 




    </script> 

    <script async defer 
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCY2buDtbYIot8Llm_FkQXHW36f0Cme6TI&callback=initMap"> 
    </script> 
0

変更順序をスクリプトの一覧

<script async defer 
     src="https://maps.googleapis.com/maps/api/js?key=keyremoved&callback=initMap"> 
</script> 
<script> 
    var geocoder = new google.maps.Geocoder(); 
    var address = "new york"; 
    // rest of the code 
</script> 
関連する問題