2015-05-06 30 views
1

我一直試圖從URL變量提供的地址生成緯度/經度,並顯示在谷歌地圖上,但地圖爲空白(緯度/長度顯然未定義)。這個問題似乎存在於getCoordinates函數中,但我無法弄清楚它是什麼。使用谷歌地圖API對LatLong進行地理編碼返回未定義

我的代碼:

<?php $address = $_GET["address"]; ?> 

<script> 
geocoder = new google.maps.Geocoder(); 

window.getCoordinates = function (address, callback) { 
    var coordinates; 
    geocoder.geocode({ address: address}, function (results, status) { 
     coords_obj = results[0].geometry.location; 
     coordinates = [coords_obj.nb,coords_obj.ob]; 
     callback(coordinates); 
    }) 
} 
</script> 

<script> 

google.maps.visualRefresh = true; 
var map; 

function initialize() { 


    getCoordinates('<?php echo $address ?>', function(coords) { 
     var mapOptions = { 
     center: new google.maps.LatLng(coords[0], coords[1]), 
     zoom: 15, 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
     }; 

     map = new google.maps.Map(document.getElementById('map-canvas'), 
      mapOptions); 

}) 

} 

google.maps.event.addDomListener(window, 'load', initialize); 

任何幫助,將不勝感激。謝謝。


***發現了問題:

我用coords_obj.nb時,我應該已經使用coords_obj.A和coords_obj.F作爲輸出由我的console.log coords_obj.ob:

[Object] 
0: Object 
address_components: Array[8] 
formatted_address: "1045 Mission Street, San Francisco, CA 94103, USA" 
geometry: Object 
location: pf 
A: 37.7800206 
F: -122.40959459999999 
__proto__: pf 
location_type: "ROOFTOP" 
viewport: ph 
__proto__: Object 
place_id: "ChIJeaMNfoSAhYARY4zPZwV_vgw" 
types: Array[1] 
__proto__: Object 
length: 1 
__proto__: Array[0] 
+2

做**不**使用API​​(coords_obj.A,coords_obj.F,coords_obj.ob或coords_obj.nb的無證特性,它們可以並且每次發佈API都會有所變化,請使用記錄的屬性.lat()和.lng()。請將您的解決方案作爲**答案**發佈,而不是對問題進行編輯(並在可以時接受) – geocodezip

+0

相關問題:[Google.Maps.Event設置 - Va與Xa](http://stackoverflow.com/questions/19816294/google-maps-event-settings-va-versus-xa) – geocodezip

+0

相關問題[Google地圖API遺漏的類型錯誤:無法讀取屬性「0」空的(http://stackoverflow.com/questions/22442876/google-map-api-uncaught-typeerror-cannot-read-property-0-of-null) – geocodezip

回答

1

謝謝geocodezip。爲了避免對未來的API更新破損,我換成:

geocoder = new google.maps.Geocoder(); 

window.getCoordinates = function (address, callback) { 
    var coordinates; 
    geocoder.geocode({ address: address}, function (results, status) { 
     coords_obj_lat = results[0].geometry.location.lat(); 
     coords_obj_lng = results[0].geometry.location.lng(); 
     coordinates = [coords_obj_lat,coords_obj_lng]; 
     callback(coordinates); 

    }) 
} 
相關問題