私の住所を経度と緯度に変換するために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が定義されていません"
あなたは 'initMap'が呼び出される前に、あなたのコードの上半分を実行している - 「' initMap'、あなたの内側 'initMap'の上にあるコードを置く - GoogleマップのAPIがロードされるとinitMapが呼び出されますあなたの目標達成に近づくでしょう。 –
'initMap'関数内でジオコーダーコードを動かしてください。マップjs URIのURLにコールバック関数があります。これは、マップスクリプトがロードされると実行されます。スクリプトが –
の[Google Maps APIで緯度と経度の代わりに住所を使用する]をロードする前に、新しい 'google.maps.Geocoder();'を呼び出しています(http://stackoverflow.com/questions/15925980/using -address-instead-of-longitude-and-latitude-google-maps-api) – geocodezip