Reputation: 21
I'm using this script to get the geo-code information from Google but I don't know how to filter out just specifics such as Lat, Lon, Town, County. Here is my code (which I beleive will work under the new API-3?):
<?php
$address="LS1 7AS";
$result=file_get_contents("http://maps.google.com/maps/api/geocode/json?address=" . urlencode($address) . "&sensor=false" );
$geocodedinfo=json_decode($result);
print_r($geocodedinfo);
?>
This prints out all of the information I need but as a block, I just want to have some of them so I can insert it into a table, for example:
$town = "town from result";
$county = "county from result";
$lat = "lat from result";
$lon = "lon from result";
Upvotes: 2
Views: 1320
Reputation: 1
Please try this:
$address="LS1 7AS";
$result = @file_get_contents("http://maps.google.com/maps/api/geocode/json?address=" . urlencode($address) . "&sensor=false" );
if ($result === FALSE) {
//manage exception from file_get_contents call
} else {
$geocodedinfo = json_decode($result);
if ($geocodedinfo->status == "OK") {
$county = "";
$town = "";
foreach ($geocodedinfo->results[0]->address_components as $addrcomps) {
if ( $addrcomps->types[0] == 'postal_town')
$town = $addrcomps->long_name;
if ( $addrcomps->types[0] == 'administrative_area_level_2')
$county = $addrcomps->long_name;
}
$lat = $geocodedinfo->results[0]->geometry->location->lat;
$lon = $geocodedinfo->results[0]->geometry->location->lng;
}
}
Sometimes the file_get_contents function calls returns an exception. So you should use @ before call it.
Upvotes: 0
Reputation: 4656
First of all You need to modify your API output format.Use output format json
because you have already used json_decode
function.
$address="LS1 7AS";
"http://maps.google.com/maps/api/geocode/json?address=" . urlencode($address) . "&sensor=false";
And you variables should look like :
$geocodedinfo=json_decode($result);
You have to check return status :
if($geocodedinfo->status == 'OK') {
$country = $geocodeinfo->results[0]->address_components[3]->long_name;
$town = $geocodeinfo->results[0]->address_components[2]->long_name;
$lat = $geocodeinfo->results[0]->geometry->location->lat;
$lon = $geocodeinfo->results[0]->geometry->location->lng;
}
Upvotes: 4