2016-01-19 108 views
3

我想創建基於谷歌地圖的城市座標,這裏是例子我現在有什麼,我總是得到錯誤?根據城市名稱獲取座標谷歌地圖

var address= 'Zurich, Ch'; 

    var geocoder = new google.maps.Geocoder(); 
    geocoder.geocode({ 'address': address}, function(results, status) { 
      if (status == google.maps.GeocoderStatus.OK) { 

      var Lat = results[0].geometry.location.lat(); 
      var Lng = results[0].geometry.location.lng(); 


      } else { 
      alert("Something got wrong " + status); 
      } 
     }); 


    var myOptions = { 
     zoom: 11, 
     center: new google.maps.LatLng(Lat,Lng), 

    }; 
+0

你什麼錯誤? – geocodezip

+0

lat未定義 –

回答

7

地理編碼器是異步的。您需要在回調函數中有/可用的地方使用返回的數據。

相關的問題:Using Address Instead Of Longitude And Latitude With Google Maps API

proof of concept fiddle

代碼片段:

function initialize() { 
 
    var address = 'Zurich, Ch'; 
 

 
    var geocoder = new google.maps.Geocoder(); 
 
    geocoder.geocode({ 
 
    'address': address 
 
    }, function(results, status) { 
 
    if (status == google.maps.GeocoderStatus.OK) { 
 
     var Lat = results[0].geometry.location.lat(); 
 
     var Lng = results[0].geometry.location.lng(); 
 
     var myOptions = { 
 
     zoom: 11, 
 
     center: new google.maps.LatLng(Lat, Lng) 
 
     }; 
 
     var map = new google.maps.Map(
 
     document.getElementById("map_canvas"), myOptions); 
 
    } else { 
 
     alert("Something got wrong " + status); 
 
    } 
 
    }); 
 
} 
 
google.maps.event.addDomListener(window, "load", initialize);
html, 
 
body, 
 
#map_canvas { 
 
    height: 100%; 
 
    width: 100%; 
 
    margin: 0px; 
 
    padding: 0px 
 
}
<script src="https://maps.googleapis.com/maps/api/js"></script> 
 
<div id="map_canvas"></div>

0

你可以使用爲getPosition()函數的座標..

document.getElementById('lat').value=marker.getPosition().lat(); 
     document.getElementById('lng').value=marker.getPosition().lng(); 

get the full code.

相關問題