问题
I'm using this code snippet to geocode an address using Google Geolocation API:
<?php
$address = "Frazione Levà - 16030 Sori (GE)";
$url = 'http://maps.google.com/maps/api/geocode/xml?address='.urlencode($address).'&sensor=false';
echo $url."\n";
$xml = file_get_contents($url);
var_dump($xml);
?>
The echo command shows the URL called is:
http://maps.google.com/maps/api/geocode/xml?address=Frazione+Lev%C3%A0+-+16030+Sori+%28GE%29&sensor=false
and the var_dump command shows the result is:
string(107) "<?xml version="1.0" encoding="UTF-8"?>
<GeocodeResponse>
<status>ZERO_RESULTS</status>
</GeocodeResponse>
"
So it seems the address cannot be geolocated.
If I call exactly the same URL above ( http://maps.google.com/maps/api/geocode/xml?address=Frazione+Lev%C3%A0+-+16030+Sori+%28GE%29&sensor=false) from my browser, I get a totally different result (the address is correctly geolocated):
<?xml version="1.0" encoding="UTF-8"?>
<GeocodeResponse>
<status>OK</status>
...
How this is possible and how I can fix it? I need to geolocate addresses from PHP.
Please note I'm using the same code snippet in a loop to geolocate hundreds of addresses every day, and it works fine on most of them; only on some addresses it shows issues like that.
回答1:
Found the solution here https://stackoverflow.com/a/10302440/2717254 thread found thanks to the StackOverflow related questions suggested in the sidebar :-)
Issue was the Region Biasing. I added ?region=it to the URL and results are now coherent.
Before adding that param, probably Google guessed it me when I loaded the page in the web browser because of headers sent by my browsers (in italian Language on Win7 italian). When I make the request from PHP, less headers are sent and probably Google thinks this is an en-US PC or something similar... :)
Also removing the ZIP code from the address also gives me coherent result across my PHP script and my web browser, but I think the ?region=it is the most clean and logically correct solution.
回答2:
In my case I solved it with language instead of region: language=it (https://developers.google.com/maps/faq#languagesupport)
来源:https://stackoverflow.com/questions/30748515/geocoding-a-specific-address-fails-from-php-works-from-browser-using-the-same-u