Google maps json geocoding, no response in browser
For whatever reason the following request gets no response from google. However if I paste the URL into the address bar it works fine. I'm not sure why this would happen. Is google filtering out requests by referrer headers?
http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=3122%2C%20Australia
开发者_StackOverflow $.ajax({
url:'http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address='+post_code+encodeURIComponent(', Australia'),
success:function(data) {
alert(data);
if(data['status'] == 'OK') {
var location = data['results'][0]['geometry']['location'];
map.panTo(location['lat']+':'+location['lng']);
map.setZoom(8);
}
}
});
It looks like you may be getting blocked by the Same Origin Policy.
You are trying to use the Server-side Geocoding Web Service when Google Maps provides a full featured Client-side Geocoding API for JavaScript. There is also a v2 version, but this has been deprecated recently.
This automatically solves your same-origin problem, and in addition the request limits would be calculated per client IP address instead of of per server IP address, which can make a huge difference for a popular site.
The client-side service should be quite easy to use. Here's a very simple geocoding example using the v3 API:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps Geocoding Demo</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
var geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({ 'address': 'Australia' }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results[0].geometry.location);
}
else {
console.log('No results found: ' + status);
}
});
}
</script>
</body>
</html>
The above should print (-25.274398, 133.775136)
to the console.
精彩评论