Recover only Name City GeoCode Maps PHP

0

I am using PHP in this code to retrieve the address, it is returning me normally, what I need is to recover only the name of the city,

$lat   =$_POST['latitude'];
$long  =$_POST['longitude'];

$address=file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$long&sensor=true");


$json_data=json_decode($address);
$full_address=$json_data->results[0]->formatted_address;

echo $full_address;
    
asked by anonymous 14.10.2015 / 23:02

1 answer

1

Try this:

<?php

function geocode($lat, $long)
{
    $url = "http://maps.googleapis.com/maps/api/geocode/json?latlng={$lat},{$long}&sensor=false";
    $content = @file_get_contents($url);
    $location = [];

    if ($content) {
        $result = json_decode(file_get_contents($url), true);

        if ($result['status'] === 'OK') {
            foreach ($result['results'][0]['address_components'] as $component) {
                switch ($component['types']) {
                    case in_array('administrative_area_level_2', $component['types']):
                        $location['administrative_area_level_2'] = $component['long_name'];
                        break;
                    case in_array('administrative_area_level_1', $component['types']):
                        $location['administrative_area_level_1'] = $component['long_name'];
                        break;
                    case in_array('country', $component['types']):
                        $location['country'] = $component['long_name'];
                        break;
                }
            }
        }
    }

    return $location;
}

$lat  = '-22.9226446';
$long = '-43.0802153';
$geocode = geocode($lat, $long);
var_dump($geocode);

// para acessar a cidade
var_dump($geocode['administrative_area_level_2']);
?>
    
15.10.2015 / 02:12