[GIS] Google Geocoder Lookup get postal code by country and city

google-maps-api

I'm currently using Google Geocoder API to determine location data for my web service.
It's important for me to get the postal code for a given country and city, but it's look like that Google is limiting the result.

Here's the API call:

http://maps.googleapis.com/maps/api/geocode/json?address=deutschland,+saarlouis&language=de&sensor=false

The result is like that:

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "Saarlouis",
               "short_name" : "Saarlouis",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Landkreis Saarlouis",
               "short_name" : "Landkreis Saarlouis",
               "types" : [ "administrative_area_level_3", "political" ]
            },
            {
               "long_name" : "Saarland",
               "short_name" : "SL",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "Deutschland",
               "short_name" : "DE",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "Saarlouis, Deutschland",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 49.36187570,
                  "lng" : 6.815549499999999
               },
               "southwest" : {
                  "lat" : 49.26046930,
                  "lng" : 6.67501510
               }
            },
            "location" : {
               "lat" : 49.31346060,
               "lng" : 6.752286499999999
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 49.36187570,
                  "lng" : 6.815549499999999
               },
               "southwest" : {
                  "lat" : 49.26046930,
                  "lng" : 6.67501510
               }
            }
         },
         "types" : [ "locality", "political" ]
      }
   ],
   "status" : "OK"
}

Best Answer

The reason you don't get the postal code is the query is too broad. If you would add a street name to the query the result will contain a postal code. A solution to your problem if you don't have a street name or don't want to use it is to split the geocoding into two parts:

Step 1: Use the city to get the GPS coordinates

https://maps.googleapis.com/maps/api/geocode/json?address=amsterdam

Step 2: Use the the GPS coordidates to get the postal code

https://maps.googleapis.com/maps/api/geocode/json?latlng=52.3182742,4.7288558


For those doing it in backend/script, here is a snippet: (using python Geocoder)

g = geocoder.google(city, key=google_api_key)
latlng = g.latlng
g_prime = geocoder.google("{},{}".format(*latlng), key=google_api_key)
postal_code = g_prime.postal