phpgoogle-maps-api-3geolocationgeocodingjquery-gmap3

Geo Coding Address - get district of a certain address (Google API)


I have a database with exact addresses (street, no, city, region/area, country). However, I was wondering if there was a way to use Google API to get the district of a city (e.g. "Manhattan") if we are in New York?

All the other information I have already in the database, so I would just need the district if there is one (of course this will be only in larger cities)...

UPDATE:

I found this function on http://www.techques.com/question/1-3151450/Google-geolocation-API---Use-longitude-and-latitude-to-get-address and tried to change formatted_address to sublocality (even others like short_name etc.) but it does not return anything... any help would be highly appreciated! Thank you!!

function reverse_geocode($lat, $lon) {
    $url = "http://maps.google.com/maps/api/geocode/json?latlng=$lat,$lon&sensor=false";
    $data = json_decode(file_get_contents($url));
    if (!isset($data->results[0]->formatted_address)){
        return "unknown Place";
    }
    return $data->results[0]->formatted_address;
}

Solution

  • You can access the sublocality like this:

    function reverse_geocode($lat, $lon) {
        $url = "http://maps.google.com/maps/api/geocode/json?latlng=$lat,$lon&sensor=false";
        $data = json_decode(file_get_contents($url));
        if (!isset($data->results[0]->address_components)){
            return "unknown Place";
        }
    
        if ($data->results[0]->address_components[2]->types[0]=="sublocality") {
    
            $return_array['type']="sublocality";
            $return_array['sublocality_long_name']=$data->results[0]->address_components[2]->long_name;
            $return_array['sublocality_short_name']=$data->results[0]->address_components[2]->short_name;
    
            return $return_array;
            }
    
    }