1
votes

https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY

I want to get city, state and zipcode from the Google API returned address.

Right now I have to explode from the following string

"formatted_address" : "1600 Amphitheatre Parkway, Mountain View, CA 94043, USA",
1
Can you provide a sample response body?Tom Davies

1 Answers

4
votes

You can use array_filter to filter the address_components field for each types :

<?php

$apiKey = "API_KEY";

$url = "https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=".$apiKey;

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
curl_close($ch);

$data = json_decode($result,true);

$components = $data["results"][0]["address_components"];

// filter the address_components field for type : $type
function filter($components, $type)
{
    return array_filter($components, function($component) use ($type) {
        return array_filter($component["types"], function($data) use ($type) {
            return $data == $type;
        });
    });
}

$zipcode = array_values(filter($components, "postal_code"))[0]["long_name"];
$citystate = array_values(filter($components, "administrative_area_level_1"))[0]["long_name"];

var_dump($zipcode);
var_dump($citystate);

?>