Google Maps API - Retrieving city and state using PHP - php

I'm currently using Google Maps API to get a longitude and latitude form the user's street, street number and zip code.
I would also like to grab their city and state from the Maps API results. The XML document formats it strangely though, and I'm not sure how I'm supposed to reference it (it's different from the way I'm grabbing the long and lat).
This is how I am loading the Maps API:
$map_address = str_replace($address."+".$zip);
$map_api_url = "https://maps.googleapis.com/maps/api/geocode/json?address=".$map_address."&key=myKey";
$resp_json = file_get_contents($map_api_url);
$resp = json_decode($resp_json, true);
I then get the Long and Lat:
$lati = $resp['results'][0]['geometry']['location']['lat'];
$longi = $resp['results'][0]['geometry']['location']['lng'];
But how do I grab the city and state?
{
"results" : [
{
"address_components" : [
{
"long_name" : "3840",
"short_name" : "3840",
"types" : [ "street_number" ]
},
{
"long_name" : "Fake Street",
"short_name" : "Fake St",
"types" : [ "route" ]
},
{
"long_name" : "Wilson Heights",
"short_name" : "Wilson Heights",
"types" : [ "neighborhood", "political" ]
},
{
"long_name" : "North York",
"short_name" : "North York",
"types" : [ "sublocality_level_1", "sublocality", "political" ]
},
{
"long_name" : "Toronto",
"short_name" : "Toronto",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Toronto Division",
"short_name" : "Toronto Division",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Ontario",
"short_name" : "ON",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "Canada",
"short_name" : "CA",
"types" : [ "country", "political" ]
},
{
"long_name" : "M6H",
"short_name" : "M6H",
"types" : [ "postal_code_prefix", "postal_code" ]
}
],
"formatted_address" : "3840 Fake Street, Toronto, ON M6H, Canada",
"geometry" : {
"location" : {
"lat" : 43.5399244,
"lng" : -78.43486559999999
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 43.5412733802915,
"lng" : -78.43351661970848
},
"southwest" : {
"lat" : 43.7385754197085,
"lng" : -79.43621458029151
}
}
},
"place_id" : "ChIJPVDxjGgyK4gRt3O7zOSmIF4",
"types" : [ "street_address" ]
}
],
"status" : "OK"
}

Just answered my own question by running the code through a loop. Please let me know if you have a better way!
foreach($resp['results'][0]['address_components'] as $address_componenets) {
if($address_componenets["types"][0]=="country") {
$country = $address_componenets["long_name"];
}
if($address_componenets["types"][0]=="administrative_area_level_1") {
$state = $address_componenets["long_name"];
}
if($address_componenets["types"][0]=="locality") {
$city = $address_componenets["long_name"];
}
}

Related

How to access json file element

So I am retrieving a json file from an API, and I want to grab the data from object 'place_id'.
I have been looking online and I have seen how to grab elements from json files, however I can't understand what I am doing wrong, as my code gives me an error:
Warning: Undefined array key "place_id" in C:\xampp\htdocs\cw\tester.php on line 15
This is my php code where I try to grab the data from 'place_id':
$place_json = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address=belfast+zoo&key=' . $place_id_key);
$json = json_decode($place_json, true);
echo $json['results']['place_id'];
this is my json file:
{
"results" : [
{
"address_components" : [
{
"long_name" : "Antrim Road",
"short_name" : "Antrim Rd",
"types" : [ "route" ]
},
{
"long_name" : "Belfast",
"short_name" : "Belfast",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Newtownabbey",
"short_name" : "Newtownabbey",
"types" : [ "postal_town" ]
},
{
"long_name" : "Belfast",
"short_name" : "Belfast",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Northern Ireland",
"short_name" : "Northern Ireland",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United Kingdom",
"short_name" : "GB",
"types" : [ "country", "political" ]
},
{
"long_name" : "BT36 7PN",
"short_name" : "BT36 7PN",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "Antrim Rd, Belfast, Newtownabbey BT36 7PN, UK",
"geometry" : {
"location" : {
"lat" : 54.6577821,
"lng" : -5.943665699999999
},
"location_type" : "GEOMETRIC_CENTER",
"viewport" : {
"northeast" : {
"lat" : 54.65913108029149,
"lng" : -5.942316719708497
},
"southwest" : {
"lat" : 54.6564331197085,
"lng" : -5.945014680291502
}
}
},
"place_id" : "ChIJ88iCe5inYUgRdeXmfCtuvu4",
"plus_code" : {
"compound_code" : "M354+4G Belfast, UK",
"global_code" : "9C6PM354+4G"
},
"types" : [ "establishment", "point_of_interest", "tourist_attraction", "zoo" ]
}
],
"status" : "OK"
}
Apologies as I know it is obvious, but I can't seem to understand why! thanks!
This should do the trick? Notice the [0] that was added. Since results is actually an array.
<?php
$place_json = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address=belfast+zoo&key=' . $place_id_key);
$json = json_decode($place_json, true);
echo $json['results'][0]['place_id'];

How to get a fields particular value of JSON in Codeigniter Php?

I'm using Google Map Api, and getting the result in JSON form and the output result is
{
"results" : [
{
"address_components" : [
{
"long_name" : "Plot No 1",
"short_name" : "Plot No 1",
"types" : [ "premise" ]
},
{
"long_name" : "B Block Road",
"short_name" : "B Block Rd",
"types" : [ "route" ]
},
{
"long_name" : "Rangpuri Extention B-Block Pocket-4",
"short_name" : "Rangpuri Extention B-Block Pocket-4",
"types" : [ "political", "sublocality", "sublocality_level_1" ]
},
{
"long_name" : "New Delhi",
"short_name" : "New Delhi",
"types" : [ "locality", "political" ]
},
{
"long_name" : "South West Delhi",
"short_name" : "South West Delhi",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Delhi",
"short_name" : "DL",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "India",
"short_name" : "IN",
"types" : [ "country", "political" ]
},
{
"long_name" : "110037",
"short_name" : "110037",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "Plot No 1, B Block Rd, Rangpuri Extention B-Block Pocket-4, New Delhi, Delhi 110037, India",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 28.5379687,
"lng" : 77.121816
},
"southwest" : {
"lat" : 28.5377897,
"lng" : 77.1217006
}
},
"location" : {
"lat" : 28.5378435,
"lng" : 77.1217523
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 28.5392281802915,
"lng" : 77.12310728029151
},
"southwest" : {
"lat" : 28.5365302197085,
"lng" : 77.12040931970849
}
}
},
"partial_match" : true,
"place_id" : "ChIJibjV7RYcDTkRnaFq2Lg__b4",
"types" : [ "premise" ]
}
],
"status" : "OK"
}
and I want to extract lat and lng,under the location object, write now I'm using this code
$mapcontent = json_decode($content,true);
$lat = $mapcontent['results'][0]['geometry']['location']['lat'];
$lng = $mapcontent['results'][0]['geometry']['location']['lng'];
where $content is the output result which mention above,by using the above code and it works but sometimes I'm getting error of undefined offest:0, on $lat and $lng line, is there any other way to retrieve specific data from the JSON Code, I already search on internet but I'm not getting any idea how to resolve this, please help me out
You can write the code like :
$mapcontent = json_decode($content,true);
$resultCount = count($mapcontent['results']);
if( $resultCount > 0 ) {
$lat = $mapcontent['results'][0]['geometry']['location']['lat'];
$lng = $mapcontent['results'][0]['geometry']['location']['lng'];
}
It will work.
$url='your url';
$array = file_get_contents($url);
$array = (array)json_decode($array);
You can also write code like.
$mapcontent = json_decode($content,true);
if( true != empty($mapcontent['results'])) {
$lat = $mapcontent['results'][0]['geometry']['location']['lat'];
$lng = $mapcontent['results'][0]['geometry']['location']['lng'];
}

Laravel reverse geocode the latitude and longitude

Im using Laravel and this dependancy https://github.com/alexpechkarev/google-geocoder to reverse geocode my latitude and longitude what I did first is to put a static lat and lng.
In my controller I have this:
public function location(){
$lat=40.714224;
$lng=-73.961452;
$param = array("latlng"=>"$lat,$lng");
$response = \Geocoder::geocode('json', $param);
return $response;
}
This returns.
{
"results" : [
{
"address_components" : [
{
"long_name" : "277",
"short_name" : "277",
"types" : [ "street_number" ]
},
{
"long_name" : "Bedford Avenue",
"short_name" : "Bedford Ave",
"types" : [ "route" ]
},
{
"long_name" : "Williamsburg",
"short_name" : "Williamsburg",
"types" : [ "neighborhood", "political" ]
},
{
"long_name" : "Brooklyn",
"short_name" : "Brooklyn",
"types" : [ "sublocality", "political" ]
},
{
"long_name" : "Kings",
"short_name" : "Kings",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "New York",
"short_name" : "NY",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
},
{
"long_name" : "11211",
"short_name" : "11211",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "277 Bedford Avenue, Brooklyn, NY 11211, USA",
"geometry" : {
"location" : {
"lat" : 40.714232,
"lng" : -73.9612889
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 40.7155809802915,
"lng" : -73.9599399197085
},
"southwest" : {
"lat" : 40.7128830197085,
"lng" : -73.96263788029151
}
}
},
"place_id" : "ChIJd8BlQ2BZwokRAFUEcm_qrcA",
"types" : [ "street_address" ]
},
],
"status" : "OK"
}
Now what I want to do is to get the "formatted_address" of the results. Can you help me with this.

Get the right values from a JSON array using Google's Geocoding API

I'm using the Google Geocoding API, and PHP (cURL) to get the JSON array.
That's all working fine.
The problem is that not every output is the same.
Example:
I have two addresses:
Dam 1, Amsterdam
Kurfürstendamm 1, Berlin
For the Amsterdam address the count of $array['results'][0]['address_components'] is 8 and the one for Berlin 7.
JSON output:
Amsterdam:
{
"results" : [
{
"address_components" : [
{
"long_name" : "1",
"short_name" : "1",
"types" : [ "street_number" ]
},
{
"long_name" : "Dam",
"short_name" : "Dam",
"types" : [ "route" ]
},
{
"long_name" : "Centrum",
"short_name" : "Centrum",
"types" : [ "sublocality_level_1", "sublocality", "political" ]
},
{
"long_name" : "Amsterdam",
"short_name" : "Amsterdam",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Amsterdam",
"short_name" : "Amsterdam",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Noord-Holland",
"short_name" : "NH",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "Nederland",
"short_name" : "NL",
"types" : [ "country", "political" ]
},
{
"long_name" : "1012 JS",
"short_name" : "1012 JS",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "Dam 1, 1012 JS Amsterdam, Nederland",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 52.3740904,
"lng" : 4.8951464
},
"southwest" : {
"lat" : 52.37303319999999,
"lng" : 4.893589
}
},
"location" : {
"lat" : 52.3735618,
"lng" : 4.8943677
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 52.37491078029149,
"lng" : 4.895716680291502
},
"southwest" : {
"lat" : 52.3722128197085,
"lng" : 4.893018719708498
}
}
},
"place_id" : "ChIJ46bYaccJxkcRR1k-7Pl25Kg",
"types" : [ "premise" ]
}
],
"status" : "OK"
}
Berlin:
{
"results" : [
{
"address_components" : [
{
"long_name" : "1",
"short_name" : "1",
"types" : [ "street_number" ]
},
{
"long_name" : "Kurfürstendamm",
"short_name" : "Kurfürstendamm",
"types" : [ "route" ]
},
{
"long_name" : "Bezirk Charlottenburg-Wilmersdorf",
"short_name" : "Bezirk Charlottenburg-Wilmersdorf",
"types" : [ "sublocality_level_1", "sublocality", "political" ]
},
{
"long_name" : "Berlin",
"short_name" : "Berlin",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Berlin",
"short_name" : "Berlin",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "Duitsland",
"short_name" : "DE",
"types" : [ "country", "political" ]
},
{
"long_name" : "10719",
"short_name" : "10719",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "Kurfürstendamm 1, 10719 Berlin, Duitsland",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 52.50440769999999,
"lng" : 13.3337799
},
"southwest" : {
"lat" : 52.5043971,
"lng" : 13.3337737
}
},
"location" : {
"lat" : 52.50440769999999,
"lng" : 13.3337737
},
"location_type" : "RANGE_INTERPOLATED",
"viewport" : {
"northeast" : {
"lat" : 52.50575138029149,
"lng" : 13.3351257802915
},
"southwest" : {
"lat" : 52.5030534197085,
"lng" : 13.3324278197085
}
}
},
"partial_match" : true,
"place_id" : "EixLdXJmw7xyc3RlbmRhbW0gMSwgMTA3MTkgQmVybGluLCBEZXV0c2NobGFuZA",
"types" : [ "street_address" ]
}
],
"status" : "OK"
}
As you can see the country and postalcode indexes are different (country: 6 and 5, postalcode 7 and 6)
When I want to show the street, housenumber, postalcode, city and country for both cities something like this:
echo 'Street = '.$array['results'][0]['address_components'][1]['long_name'].'<br />';
echo 'Housenumber = '.$array['results'][0]['address_components'][0]['long_name'].'<br />';
echo 'Postalcode = '.$array['results'][0]['address_components'][7]['long_name'].'<br />';
echo 'City = '.$array['results'][0]['address_components'][3]['long_name'].'<br />';
echo 'Country = '.$array['results'][0]['address_components'][6]['long_name'].'<br />';
It shows the following output:
Amsterdam:
Street = Dam
Housenumber = 1
Postalcode = 1012 JS
City = Amsterdam
Country = Netherlands
Berlin:
Street = Kurfürstendamm
Housenumber = 1
Notice: Undefined offset: 7 in .... on line ....
Postalcode =
City = Berlin
Country = 10719
So the question is, how can I get the "long_name" per "types" in the "address_components" array?
Or maybe there are even better ways?
You could try the following code below to convert the JSON reponse to an array with the address components as keys:
function convertAddress($json)
{
$data = json_decode($json);
$address = array();
foreach($data['results']['address_components'] AS $_component){
$key = array_values($_component['types']);
$address[$key[0]] = $_component;
}
return $address;
}
This works great for me with your test data, you can then access data like so:
$address = convertAddress($berlin_address);
print $address['post_code']['long_name'];
Please note I have only worked on the address_components part of the JSON, the rest should be easy to work into the method though.

Parsing Google Maps API for Latitude and Longitude

I am trying to get the lat/lng of an address with the Google maps API. I am having trouble parsing the JSON result just to store the lat and lng values as PHP variables. Anyone able to help me parse this?
This is what I have so far:
<?php
$jsonObject = file_get_contents(
"http://maps.googleapis.com/maps/api/geocode/json?
address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true");
$object = json_decode($jsonObject);
$lat = $object->results[0]->geometry[0]->location[0]->lat;
$lng = $object->results[0]->geometry[0]->location[0]->lng;
echo "$lat, $lng";
?>
This is the JSON feed (the lat/lng values are about two-thirds the way down the code):
{
"results" : [
{
"address_components" : [
{
"long_name" : "1600",
"short_name" : "1600",
"types" : [ "street_number" ]
},
{
"long_name" : "Amphitheatre Parkway",
"short_name" : "Amphitheatre Pkwy",
"types" : [ "route" ]
},
{
"long_name" : "Mountain View",
"short_name" : "Mountain View",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Santa Clara",
"short_name" : "Santa Clara",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "California",
"short_name" : "CA",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
},
{
"long_name" : "94043",
"short_name" : "94043",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "1600 Amphitheatre Parkway, Mountain View, CA 94043, USA",
"geometry" : {
"location" : {
"lat" : 37.4216410,
"lng" : -122.08550160
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 37.42298998029150,
"lng" : -122.0841526197085
},
"southwest" : {
"lat" : 37.42029201970850,
"lng" : -122.0868505802915
}
}
},
"types" : [ "street_address" ]
}
],
"status" : "OK"
}
geometry and location aren't arrays, try
$lat = $object->results[0]->geometry->location->lat;
$lng = $object->results[0]->geometry->location->lng;

Categories