Google Maps Geocode API only works via browser

2019-08-15 19:17发布

问题:

I try to retrieve the latitude and longitude data by postalcode/zipcode.

This is the URL that I'm using:

http://maps.google.com/maps/api/geocode/json?address=9462AA

The url returns JSON data (including latitude/longitude values) once I open it via the browser.

But when I call the exact same URL via the PHP file_get_contents method, it returns 'ZERO_RESULTS'.

$url = 'http://maps.google.com/maps/api/geocode/json?address=9462AA';
$geocode = file_get_contents($url);

echo $url; 
echo $geocode;

This prints the following result:

URL: http://maps.google.com/maps/api/geocode/json?address=9462AA

Geocode:

{
   "results" : [],
   "status" : "ZERO_RESULTS"
}

What am I doing wrong?

Thank you!

回答1:

Putting a space after the postalcode digits, in my case between 9462 and AA, works with file_get_contents.

Conclusion: via the browser you can do an API call with or without a space or '+' between the digits and characters, and in PHP you need to seperate those with a space or '+'.

The final URL became:

http://maps.google.com/maps/api/geocode/json?address=9462+AA