Use PHP to read an array of objects from Google Maps API - php

This seems like such a rookie question but I'm just banging my head against the keyboard here and I can't find anything answered already that gets me moving forward.
Scenario is I'm trying to get the Lat/Lng of a zip code by geocoding it with Google Maps API. I've gotten the results back from Google Maps API as a JSON string and I've used json_decode to put it into a PHP array. But it looks likt it's an array of objects and i'm stumped on how I can drill down into the data to get my lat/lng value.
Here is the current road block... code then results:
<?php
$jsonData = '{"results":[{"address_components":[{"long_name":"33647","short_name":"33647","types":["postal_code"]},{"long_name":"Tampa","short_name":"Tampa","types":["locality","political"]},{"long_name":"Florida","short_name":"FL","types":["administrative_area_level_1","political"]},{"long_name":"United States","short_name":"US","types":["country","political"]}],"formatted_address":"Tampa, FL 33647, USA","geometry":{"bounds":{"northeast":{"lat":28.17150,"lng":-82.26235779999999},"southwest":{"lat":28.07291710,"lng":-82.42569910}},"location":{"lat":28.14343180,"lng":-82.33433749999999},"location_type":"APPROXIMATE","viewport":{"northeast":{"lat":28.17150,"lng":-82.26235779999999},"southwest":{"lat":28.07291710,"lng":-82.42569910}}},"types":["postal_code"]}],"status":"OK"}';
$phpArray = json_decode($jsonData);
print_r($phpArray);
foreach ($phpArray as $key => $value) {
echo "<p>$key | $value</p>";
}
?>
Results:
stdClass Object ( [results] => Array ( [0] => stdClass Object ( [address_components] => Array ( [0] => stdClass Object ( [long_name] => 33647 [short_name] => 33647 [types] => Array ( [0] => postal_code ) ) [1] => stdClass Object ( [long_name] => Tampa [short_name] => Tampa [types] => Array ( [0] => locality [1] => political ) ) [2] => stdClass Object ( [long_name] => Florida [short_name] => FL [types] => Array ( [0] => administrative_area_level_1 [1] => political ) ) [3] => stdClass Object ( [long_name] => United States [short_name] => US [types] => Array ( [0] => country [1] => political ) ) ) [formatted_address] => Tampa, FL 33647, USA [geometry] => stdClass Object ( [bounds] => stdClass Object ( [northeast] => stdClass Object ( [lat] => 28.1715 [lng] => -82.2623578 ) [southwest] => stdClass Object ( [lat] => 28.0729171 [lng] => -82.4256991 ) ) [location] => stdClass Object ( [lat] => 28.1434318 [lng] => -82.3343375 ) [location_type] => APPROXIMATE [viewport] => stdClass Object ( [northeast] => stdClass Object ( [lat] => 28.1715 [lng] => -82.2623578 ) [southwest] => stdClass Object ( [lat] => 28.0729171 [lng] => -82.4256991 ) ) ) [types] => Array ( [0] => postal_code ) ) ) [status] => OK )
results | Array
status | OK
URL used to create the input JSON:
http://maps.googleapis.com/maps/api/geocode/json?address=33647&sensor=false
Looking for some help to pull out the Lat and Long values out into a PHP variable.
Thanks in advance!
Josh

The value of results is in fact another array - so you need to dig into the array to get the values you need.
This page (http://json.parser.online.fr/) might help you to visualize the data a bit more clearly.
Here's a terrible example with your data to demonstrate the depth (arrays as values):
<?php
$jsonData = '{"results":[{"address_components":[{"long_name":"33647","short_name":"33647","types":["postal_code"]},{"long_name":"Tampa","short_name":"Tampa","types":["locality","political"]},{"long_name":"Florida","short_name":"FL","types":["administrative_area_level_1","political"]},{"long_name":"United States","short_name":"US","types":["country","political"]}],"formatted_address":"Tampa, FL 33647, USA","geometry":{"bounds":{"northeast":{"lat":28.17150,"lng":-82.26235779999999},"southwest":{"lat":28.07291710,"lng":-82.42569910}},"location":{"lat":28.14343180,"lng":-82.33433749999999},"location_type":"APPROXIMATE","viewport":{"northeast":{"lat":28.17150,"lng":-82.26235779999999},"southwest":{"lat":28.07291710,"lng":-82.42569910}}},"types":["postal_code"]}],"status":"OK"}';
$phpArray = json_decode($jsonData,true);
print_r($phpArray);
foreach ($phpArray as $key => $value) {
if ( $key == "results") {
foreach ($value as $key2 => $value2) {
foreach ($value2 as $key3 => $value3) {
echo "<p>$key3 | $value3</p>";
}
}
}
}
?>
You'll need to dig down a couple of levels to find the ll data you want. This should point you in the right direction though.

Related

json object to array convert using php

I want to echo value in the json array one by one when i want
<?php
function get_web_page($url) {
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false // don't return headers
);
$ch = curl_init($url);
curl_setopt_array($ch, $options);
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
$response = get_web_page("http://maps.googleapis.com/maps/api/geocode/json?address=colombo");
$resArr = array();
$resArr = json_decode($response);
echo "<pre>";
print_r($resArr);
echo "</pre>";
echo "<br>";
echo "<br>";
;
?>
This is the current result in the browser above code
stdClass Object
(
[results] => Array
(
[0] => stdClass Object
(
[address_components] => Array
(
[0] => stdClass Object
(
[long_name] => Colombo
[short_name] => Colombo
[types] => Array
(
[0] => locality
[1] => political
)
)
[1] => stdClass Object
(
[long_name] => Colombo
[short_name] => Colombo
[types] => Array
(
[0] => administrative_area_level_2
[1] => political
)
)
[2] => stdClass Object
(
[long_name] => Western Province
[short_name] => WP
[types] => Array
(
[0] => administrative_area_level_1
[1] => political
)
)
[3] => stdClass Object
(
[long_name] => Sri Lanka
[short_name] => LK
[types] => Array
(
[0] => country
[1] => political
)
)
)
[formatted_address] => Colombo, Sri Lanka
[geometry] => stdClass Object
(
[bounds] => stdClass Object
(
[northeast] => stdClass Object
(
[lat] => 6.9805844
[lng] => 79.8900852
)
[southwest] => stdClass Object
(
[lat] => 6.8625113
[lng] => 79.8225192
)
)
[location] => stdClass Object
(
[lat] => 6.9270786
[lng] => 79.861243
)
[location_type] => APPROXIMATE
[viewport] => stdClass Object
(
[northeast] => stdClass Object
(
[lat] => 6.9805844
[lng] => 79.8900852
)
[southwest] => stdClass Object
(
[lat] => 6.8625113
[lng] => 79.8225192
)
)
)
[place_id] => ChIJA3B6D9FT4joRjYPTMk0uCzI
[types] => Array
(
[0] => locality
[1] => political
)
)
)
[status] => OK
)
I want to echo value by value
try it with:
$resArr = json_decode($response, true);
It will convert it into associative array format.
For more detail have a look at JSON Decode PHP

Access values in PHP object

I have the following PHP object, which I want to access specific values from it but I have difficulties in understanding how to start:
kamranahmedse\Geocode Object (
[service_url:kamranahmedse\Geocode:private] => http://maps.googleapis.com/maps/api/geocode/json?sensor=false
[service_results:kamranahmedse\Geocode:private] => stdClass Object (
[results] => Array (
[0] => stdClass Object (
[address_components] => Array (
[0] => stdClass Object (
[long_name] => 112
[short_name] => 112
[types] => Array (
[0] => street_number
)
)
[1] => stdClass Object (
[long_name] => Imittou
[short_name] => Imittou
[types] => Array (
[0] => route
)
)
[2] => stdClass Object (
[long_name] => Cholargos
[short_name] => Cholargos
[types] => Array (
[0] => locality
[1] => political
)
)
[3] => stdClass Object (
[long_name] => Cholargos
[short_name] => Cholargos
[types] => Array (
[0] => administrative_area_level_5
[1] => political
)
) ...
For example how can I access:
[long_name] => Cholargos
The variable you're trying to access is private and therefore you're not going to be able to access it directly.
A better way is to use the methods provided by the class you're using.
Looking at the code you've provided I can see that you're using https://github.com/kamranahmedse/php-geocode
Here's an example of how it can be used to get the locality:
<?php
require __DIR__."/vendor/autoload.php";
use kamranahmedse\Geocode;
$address = "Imittou 112 Cholargos 155 61 Greece";
$geocode = new Geocode($address);
echo $geocode->getLocality();
Also, looking at the class source code we can see that when the address information is retrieved and local variables populated the long_name is used to populate the locality, which is what you want:
$this->locality = $component->long_name;
So the above code example should answer your question.

How to converting postcode to lat/long using Google Maps API with PHP?

I am using PHP to convert a list of postcodes + County into latitude and longitude. I have tried using the google map api and the simplexml_load_file() function like so:
$url ="http://maps.googleapis.com/maps/api/geocode/xml?address=WS9+8NS,+West+Midlands&sensor=false";
$result = simplexml_load_file($url);
print"<pre>";
print_r($result);
Now this works fine as I am able to get the following:
SimpleXMLElement Object
(
[status] => OK
[result] => SimpleXMLElement Object
(
[type] => postal_code
[formatted_address] => Walsall, Walsall, West Midlands WS9 8NS, UK
[address_component] => Array
(
[0] => SimpleXMLElement Object
(
[long_name] => WS9 8NS
[short_name] => WS9 8NS
[type] => postal_code
)
[1] => SimpleXMLElement Object
(
[long_name] => Walsall
[short_name] => Walsall
[type] => Array
(
[0] => locality
[1] => political
)
)
[2] => SimpleXMLElement Object
(
[long_name] => Walsall
[short_name] => Walsall
[type] => postal_town
)
[3] => SimpleXMLElement Object
(
[long_name] => West Midlands
[short_name] => West Mids
[type] => Array
(
[0] => administrative_area_level_2
[1] => political
)
)
[4] => SimpleXMLElement Object
(
[long_name] => United Kingdom
[short_name] => GB
[type] => Array
(
[0] => country
[1] => political
)
)
)
[geometry] => SimpleXMLElement Object
(
[location] => SimpleXMLElement Object
(
[lat] => 52.6030230
[lng] => -1.9175368
)
[location_type] => APPROXIMATE
[viewport] => SimpleXMLElement Object
(
[southwest] => SimpleXMLElement Object
(
[lat] => 52.6013713
[lng] => -1.9188871
)
[northeast] => SimpleXMLElement Object
(
[lat] => 52.6040692
[lng] => -1.9161892
)
)
[bounds] => SimpleXMLElement Object
(
[southwest] => SimpleXMLElement Object
(
[lat] => 52.6020654
[lng] => -1.9182516
)
[northeast] => SimpleXMLElement Object
(
[lat] => 52.6033751
[lng] => -1.9168247
)
)
)
)
)
Problem now is, how should I take out the first latitude / longitude and not the whole thing, I only need these two values.
Please note that the lat/long are dynamic as the address changes for each search.
From the print_r you can see the structure of the content. Then, it is a matter of following it.
This contains the values:
$result->result->geometry->location
So to print them separately, you can say:
print "lat: " . $result->result->geometry->location->lat;
print "lng: " . $result->result->geometry->location->lng;
All together:
$url ="http://maps.googleapis.com/maps/api/geocode/xml?address=WS9+8NS,+West+Midlands&sensor=false";
$result = simplexml_load_file($url);
print "lat: " . $result->result->geometry->location->lat . " <br/>";
print "lng: " . $result->result->geometry->location->lng . " <br/>";
Better to use their JSON API.
$url ="http://maps.googleapis.com/maps/api/geocode/json?address=WS9+8NS,+West+Midlands&sensor=false";
$result = file_get_contents($url);
print"<pre>";
$resultArray = json_decode($result, true);
print_r($result);
Then just access like an array!
e.g.
$resultArray['results']['geometry']['location']['lat']
$resultArray['results']['geometry']['location']['lng']
I would use cURL instead of file get contents as it gives more control. But this works fine.
I would also check the $resultArray before attempting to do anything with it.

Google geocode. Parsing JSON issue

I want to get a users city, state/province, country from a google geocode of their postal/zip code (canada/usa). I retrieve the data as JSON: https://developers.google.com/maps/documentation/geocoding/#JSON
The problem is that there is not always the same amount/order of 'address_components'. I was using just like: $geocodedinfo['results'][0]['address_components'][3]['short_name'];
But I soon realized that that will not always be province/state because sometimes google will add an extra element under 'address_components'.
Is there a way to parse the results just for the specifics I need (ie: City, State/Province, Country)?
EDIT I actually decode the JSON when I get it json_decode($result, true)
Array
(
[results] => Array
(
[0] => Array
(
[address_components] => Array
(
[0] => Array
(
[long_name] => V2X 2P6
[short_name] => V2X 2P6
[types] => Array
(
[0] => postal_code
)
)
[1] => Array
(
[long_name] => Maple Ridge
[short_name] => Maple Ridge
[types] => Array
(
[0] => locality
[1] => political
)
)
[2] => Array
(
[long_name] => Maple Ridge
[short_name] => Maple Ridge
[types] => Array
(
[0] => administrative_area_level_3
[1] => political
)
)
[3] => Array
(
[long_name] => Greater Vancouver Regional District
[short_name] => Greater Vancouver Regional District
[types] => Array
(
[0] => administrative_area_level_2
[1] => political
)
)
[4] => Array
(
[long_name] => British Columbia
[short_name] => BC
[types] => Array
(
[0] => administrative_area_level_1
[1] => political
)
)
[5] => Array
(
[long_name] => Canada
[short_name] => CA
[types] => Array
(
[0] => country
[1] => political
)
)
)
[formatted_address] => Maple Ridge, BC V2X 2P6, Canada
[geometry] => Array
(
[bounds] => Array
(
[northeast] => Array
(
[lat] => 49.2214351
[lng] => -122.6577849
)
[southwest] => Array
(
[lat] => 49.219268
[lng] => -122.663613
)
)
[location] => Array
(
[lat] => 49.2202679
[lng] => -122.660587
)
[location_type] => APPROXIMATE
[viewport] => Array
(
[northeast] => Array
(
[lat] => 49.2217005303
[lng] => -122.6577849
)
[southwest] => Array
(
[lat] => 49.2190025697
[lng] => -122.663613
)
)
)
[types] => Array
(
[0] => postal_code
)
)
)
[status] => OK
)
You're going to have to loop over the results.
Most of the relevant PHP functions don't support multidimensional arrays, and the ones that do will be looping anyway.
You'll probably want something like this:
foreach ($geocodedinfo["results"] as $result) {
foreach ($result["address_components"] as $address) {
// Repeat the following for each desired type
if (in_array("country", $address["types"])) {
$country = $address["long_name"];
}
}
}
You can run the results through a foreach loop and get the data out you are looking for.
I'm taking a best guess at the meanings of the Google types, I may be off on those.
$translate = array(
'locality' => 'city',
'administrative_area_level_3' => 'area', // not sure what this one is
'administrative_area_level_2' => 'county', // regional district ?
'administrative_area_level_1' => 'state', // province
'country' => 'country',
'postal_code' => 'zip', // postal code
);
$address_components = array( );
foreach ($geocodedinfo['results'][0]['address_components'] as $component) {
$address_components[$translate[$component['type'][0]]] = $component['long_name'];
}
var_dump($address_components);
try looking at this, http://php.net/manual/en/control-structures.foreach.php it's for looping over arrays, you can do something like,
foreach ($result['results'][0]['address_components'] as $key => $val)
{
if (in_array('country', $result['results'][0]['address_components'][$key]['types'][0]))
{
echo $result['results'][0]['address_components'][$key]['long_name'];
}
}
Something like that should work
// parse the json response
$jsondata = json_decode($data,true);
$results = $jsondata['results'][0];
$addr =$results['formatted_address'];
This allows you to access the long formatted address
326 London Road, Newbury, Berkshire, West Berkshire RG14 2DA, UK

Iterate through SimpleXMLElement to retrieve postal code value

I am trying to extract the postal code from the Google Geocode v3 API XML Response. The difficulty I am having is that sometimes the postal_code value is contained in the 6th address_element and sometimes in the 7th. Here is the XML response that I am working with and in this sample response you can see that the postal_code is the 6th element of the address_component array:
SimpleXMLElement Object
(
[status] => OK
[result] => Array
(
[0] => SimpleXMLElement Object
(
[type] => street_address
[formatted_address] => 177 Church St, Toronto, ON M5C 2G5, Canada
[address_component] => Array
(
[0] => SimpleXMLElement Object
(
[long_name] => 177
[short_name] => 177
[type] => street_number
)
[1] => SimpleXMLElement Object
(
[long_name] => Church St
[short_name] => Church St
[type] => route
)
[2] => SimpleXMLElement Object
(
[long_name] => Toronto
[short_name] => Toronto
[type] => Array
(
[0] => locality
[1] => political
)
)
[3] => SimpleXMLElement Object
(
[long_name] => Toronto
[short_name] => Toronto
[type] => Array
(
[0] => administrative_area_level_2
[1] => political
)
)
[4] => SimpleXMLElement Object
(
[long_name] => Ontario
[short_name] => ON
[type] => Array
(
[0] => administrative_area_level_1
[1] => political
)
)
[5] => SimpleXMLElement Object
(
[long_name] => Canada
[short_name] => CA
[type] => Array
(
[0] => country
[1] => political
)
)
[6] => SimpleXMLElement Object
(
[long_name] => M5C 2G5
[short_name] => M5C 2G5
[type] => postal_code
)
)
[geometry] => SimpleXMLElement Object
(
[location] => SimpleXMLElement Object
(
[lat] => 43.6547363
[lng] => -79.3763746
)
[location_type] => RANGE_INTERPOLATED
[viewport] => SimpleXMLElement Object
(
[southwest] => SimpleXMLElement Object
(
[lat] => 43.6533849
[lng] => -79.3777345
)
[northeast] => SimpleXMLElement Object
(
[lat] => 43.6560829
[lng] => -79.3750365
)
)
[bounds] => SimpleXMLElement Object
(
[southwest] => SimpleXMLElement Object
(
[lat] => 43.6547315
[lng] => -79.3763964
)
[northeast] => SimpleXMLElement Object
(
[lat] => 43.6547363
[lng] => -79.3763746
)
)
)
)
I haven't tried this, but I think it should work.
$address = $array->result[0]->address_component;
$postal_code = '';
foreach($address as $adr){
if($adr->type == 'postal_code'){
$postal_code = $adr->long_name;
}
}

Categories