How to call google map geocode service with jquery ajax
I'm trying to get the LatLng from google map geocode api. my code is below with开发者_JS百科 address values is "New York, NY"
$.ajax({
url: 'http://maps.googleapis.com/maps/api/geocode/json',
data: {
sensor: false,
address: address
},
success: function (data) {
alert(data)
}
});
But I'm not getting any values in alert.
Thanks for any help.
You will need to contact the API regarding the rules.
$.getJSON( {
url : 'https://maps.googleapis.com/maps/api/geocode/json',
data : {
sensor : false,
address : address
},
success : function( data, textStatus ) {
console.log( textStatus, data );
}
} );
Edit:
How dumb of me, shouldn't be on stackoverflow in the morning! The problem is a cross-domain request. For security reasons this is not allowed. See: How to make cross-domain AJAX calls to Google Maps API?
Please use Google's own Geocoding client.
there is no need to make use of jquery, Google maps javascript API v3 has build in its own functions which makes the API easy to use.
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
});
}
});
If anyone is seeking help on this topic, this is how I have done it. Note this is a reverse lookup, but a forward lookup should work the same way:
`
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;
});
}`
V3 geocoding webservice doesn't support JSONP requests, but it's still available in V2
See: http://blog.futtta.be/2010/04/09/no-more-jsonp-for-google-geocoding-webservice/
This is how I did it. Geocoder seems like is creating it's own callback.
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();
}
});
or specify dataType to jsonp?
$.ajax({
url: 'http://maps.googleapis.com/maps/api/geocode/json',
data: {
sensor: false,
address: address
},
dataType:'jsonp',
success: function (data) {
alert(data)
}
});
精彩评论