Recover Only Geocode City Name Maps PHP

Asked

Viewed 350 times

0

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

$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;

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']);
?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.