2011-03-04 49 views
12

我試圖從Google地圖地理編碼API獲取LatLng。我的代碼是低於地址值是「紐約,紐約」如何使用jquery ajax調用Google地圖地理編碼服務

$.ajax({ 
    url: 'http://maps.googleapis.com/maps/api/geocode/json', 
    data: { 
     sensor: false, 
     address: address 
    }, 
    success: function (data) { 
     alert(data) 
    } 
}); 

但我沒有得到任何值的警報。

感謝您的任何幫助。

+1

你想說什麼?請使用Firebug(或同等產品)進行調試。 te請求包含什麼內容? – 2011-03-04 08:29:33

+0

@Fokko Driesprong檢查螢火蟲,獲取數據爲空和網址爲http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=NewYork%2C+NY,並在瀏覽器地址中粘貼此網址時給結果的酒吧。 :-) – rajakvk 2011-03-04 08:33:01

回答

13

您將需要聯繫有關rules的API。

$.getJSON({ 
    url : 'https://maps.googleapis.com/maps/api/geocode/json', 
    data : { 
     sensor : false, 
     address : address 
    }, 
    success : function(data, textStatus) { 
     console.log(textStatus, data); 
    } 
}); 

編輯:

如何愚蠢的我,不應該在早晨計算器!問題是跨域請求。出於安全原因,這是不允許的。請參閱:How to make cross-domain AJAX calls to Google Maps API?

請使用Google自己的Geocoding client

+0

再次感謝。我試着用上面的代碼,但沒有運氣。順便說一句,函數之前我添加了「成功:」 – rajakvk 2011-03-04 08:44:11

+0

試試這個例子http://jsfiddle.net/ipsjolly/FSU6r/ – 2014-04-14 09:03:48

+0

我試過這個解決方案,但我得到「未捕獲的SyntaxError:意外的標識符」地址參數錯誤數據中。有人可以幫我解決這個問題嗎? – 2016-09-19 21:12:03

0

或指定dataType爲jsonp?

$.ajax({ 
    url: 'http://maps.googleapis.com/maps/api/geocode/json', 
    data: { 
     sensor: false, 
     address: address 
    }, 
    dataType:'jsonp', 
    success: function (data) { 
     alert(data) 
    } 
}); 
1

這是我做到了。 Geocoder似乎正在創建它自己的回調。

geo.geocode({ 'address': myaddress }, function(data, status) { 
    if (status == google.maps.GeocoderStatus.OK) { 
     var myylocation = data[0].geometry.location; 
     lat = myylocation.lat(); 
     lng = myylocation.lng(); 
    } 
}); 
1

如果有人在這個話題上尋求幫助,這就是我已經做到的。請注意,這是一個反向查找,但正向查找應工作方式相同:

`

function getLocation() { 
var latdegrees=40.2298; 
var londegrees=-41.88754; 
    var url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + latdegrees + "," + londegrees + "YOUR API KEY"; 
    $.getJSON(url,function (data, textStatus) { 
      var streetaddress=data.results[0].formatted_address; 
      return streetaddress; 
     }); 
    }` 
8

沒有必要使使用jQuery的,谷歌地圖JavaScript API V3已經建立了自己的職能這使得API易於使用。

https://developers.google.com/maps/documentation/javascript/geocoding https://developers.google.com/maps/documentation/geocoding/intro

var geocoder = new google.maps.Geocoder(); 
geocoder.geocode({ 'address': address }, function(results, status) { 
    if (status == google.maps.GeocoderStatus.OK) { 
     map.setCenter(results[0].geometry.location); 
     var marker = new google.maps.Marker({ 
      map: map, 
      position: results[0].geometry.location 
     }); 
    } 
}); 
相關問題