Asesha George
Asesha George

Reputation: 2268

best way to get city name from google reverse geocoding api php

i am trying to get city name from google reverse geocoding api, my code is displaying full address of the location but i need only city. bellow is my code

<?php
session_start();
if(!empty($_POST['latitude']) && !empty($_POST['longitude'])){
    //Send request and receive json data by latitude and longitude
    $url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.trim($_POST['latitude']).','.trim($_POST['longitude']).'&sensor=false';
    $json = @file_get_contents($url);
    $data = json_decode($json);
    $status = $data->status;
    if($status=="OK"){
        //Get address from json data
        //$location = $data->results[0]->formatted_address;
        $location = $data->results[0]->address_components;

    }else{
        $location =  '';
    }
    //Print city
    $_SESSION['getgeoloc']=$location[6]->long_name;

    echo $location;
}
?>

i tried below code to display city, but some times its showing zip code and sometimes city name

$_SESSION['getgeoloc']=$location[6]->long_name;

is there any best way ?

Upvotes: 1

Views: 9089

Answers (2)

andreshg112
andreshg112

Reputation: 722

You can specify a result_type = locality in the query params like shown below.

enter image description here

For more information about filters, you can search for Optional parameters in a reverse Geocoding request documentation.

https://developers.google.com/maps/documentation/geocoding/intro#ReverseGeocoding

Upvotes: 0

Asesha George
Asesha George

Reputation: 2268

Here is the solution,

<?php
    $lat = $_POST['lat'];
    $lng = $_POST['lng'];

    $url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.$lat.','.$lng.'&sensor=false';
    $json = @file_get_contents($url);
    $data = json_decode($json);
    $status = $data->status;
    if($status=="OK") {
        //Get address from json data
        for ($j=0;$j<count($data->results[0]->address_components);$j++) {
            $cn=array($data->results[0]->address_components[$j]->types[0]);
            if(in_array("locality", $cn)) {
                $city= $data->results[0]->address_components[$j]->long_name;
            }
        }
     } else{
       echo 'Location Not Found';
     }
     //Print city 
     echo $city;

This has solved my problem and works great. The main part is the for loop,

for ($j=0;$j<count($data->results[0]->address_components);$j++) {
    $cn=array($data->results[0]->address_components[$j]->types[0]);
    if (in_array("locality", $cn)) {
        $city= $data->results[0]->address_components[$j]->long_name;
    }
}

Hope this helps.

Upvotes: 9

Related Questions