Reputation:
I have this php to grab data from google servers about specific geolocation.
<?php
if ($_GET['latitude'] AND $_GET['longitude']) {
$lat = $_GET['latitude'];
$lng = $_GET['longitude'];
echo json_encode(reverse_geocode($lat,$lng));
}
?>
<?php
//Get STATE from Google GeoData
function reverse_geocode($lat,$lng) {
$url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$lng&sensor=false";
$result = file_get_contents("$url");
$json = json_decode($result);
foreach ($json->results as $result) {
foreach($result->address_components as $addressPart) {
//print_r($addressPart);
if((in_array('locality', $addressPart->types)) && (in_array('political', $addressPart->types))) {
$city = $addressPart->long_name;
}
else if((in_array('administrative_area_level_1', $addressPart->types)) && (in_array('political', $addressPart->types))) {
$state = $addressPart->long_name;
}
else if((in_array('country', $addressPart->types)) && (in_array('political', $addressPart->types))) {
$country = $addressPart->long_name;
}
else if(in_array('route', $addressPart->types)) {
$street = $addressPart->long_name;
}
else if(in_array('street_number', $addressPart->types)) {
$street_number = $addressPart->long_name;
}
else if(in_array('postal_code', $addressPart->types)) {
$postal_code = $addressPart->long_name;
}
}
}
//return $address;
return array('country' => $country, 'state' => $state, 'city' => $city, 'street' => $street_number . " " . $street, 'zip' => $postal_code);
//print_r($json);
}
?>
For ?latitude=49.260441796677014&longitude=-123.12049284766846
This returns:
{"country":"Canada","state":"British Columbia","city":"Vancouver","street":"706-750 West 12th Avenue","zip":"V5Z"}
Notice zip, it is 3 letter prefix of postal code, not real postal code. Why is this happening? In original json data it seemed I had full postal code. Uncomment print_r($addressPart);
to see what I'm talking about.
Upvotes: 0
Views: 2214
Reputation: 117334
The $addressPart
where the postal_code
has been taken from contains the type postal_code
, but when you inspect the response you'll see that it also contains the type postal_code_prefix
.... and that's what you got. Skip the $addressPart
when the types contains postal_code_prefix
else if(in_array('postal_code', $addressPart->types)
&& !in_array('postal_code_prefix', $addressPart->types)){
//....
}
Upvotes: 2