The easiest way to get the zip code on behalf of the city

I wanted to chat with my assignment and search the weather by the name of the city, not by zip code (as I configured it now). What would be the easiest way to use the city name input line and get the postal code from it? Help is much appreciated! Thanks!

+6
source share
4 answers

Google can help you here!

https://developers.google.com/maps/documentation/geocoding/

The zip code is actually called Google Postal_code.

"long_name": "94043", "short_name": "94043", "types": postal_code 

For example, let's say you want to get a zip for Clarkston, MI ...

http://maps.googleapis.com/maps/api/geocode/json?address=Clarkston+MI&sensor=true

This returns:

 { "results" : [ { "address_components" : [ { "long_name" : "Clarkston", "short_name" : "Clarkston", "types" : [ "locality", "political" ] }, { "long_name" : "Oakland", "short_name" : "Oakland", "types" : [ "administrative_area_level_2", "political" ] }, { "long_name" : "Michigan", "short_name" : "MI", "types" : [ "administrative_area_level_1", "political" ] }, { "long_name" : "United States", "short_name" : "US", "types" : [ "country", "political" ] }, { "long_name" : "48346", "short_name" : "48346", "types" : [ "postal_code" ] } ], "formatted_address" : "Clarkston, MI 48346, USA", "geometry" : { "bounds" : { "northeast" : { "lat" : 42.7418310, "lng" : -83.41402409999999 }, "southwest" : { "lat" : 42.7252370, "lng" : -83.42880730000002 } }, "location" : { "lat" : 42.73511960, "lng" : -83.41929410 }, "location_type" : "APPROXIMATE", "viewport" : { "northeast" : { "lat" : 42.74331460, "lng" : -83.40328670 }, "southwest" : { "lat" : 42.72692350, "lng" : -83.43530149999999 } } }, "types" : [ "locality", "political" ] } ], "status" : "OK" } 

EDIT

If you do not receive a postal code with this first call, you will have to make a second call to the same web service using the coordinates from the first call. Still very simple - a call to Stevens Point WI would be as follows:

http://maps.googleapis.com/maps/api/geocode/json?latlng=44.52357920000001,-89.5745630&sensor=true

You can capture lat / lng values ​​from "location". Hope this helps!

+13
source

The most popular answer above is incomplete. Please check out my more relevant answer below, where I will describe my personal proven method to get the most accurate results from the Google Maps API. Tested on a site with over 100 million unique locations.

Each city has many zip codes.

I had a problem like this when I had to generate over 1 million link combinations for sitemaps with mixed locations + keywords.

At first I tried to add the keywords “center”, “central” and “center” to the name of the city and country, and this worked in 80% of cases, which was not good enough due to the volume that I had to fulfill.

Therefore, I continued to search for the best solution and eventually found 2 NEW parameters for the Google Geocode Maps API, simply copying / pasting some of the results into the request URL.

Please note: this is not documented by Google, and although it only works now, it may not work in the future.

1st parameter:

 &components=country:UK // where "UK" is a country of choice, by utilising this method, rather than adding the Country to the City name, you will avoid clashes and reduce the risk of not getting the postcode. 

2nd parameter:

 &location_type=GEOMETRIC_CENTER& // as is, this will get you a place closest to the central geometrical location of the town/city. 

Full example:

 var city_name = 'Edinburgh'; // City/Town/Place Name var country_code = 'GB'; // Great Britain var key = 'AIzaSyBk********************cM' // Google API Key var query = https://maps.googleapis.com/maps/api/geocode/json?address='+city_name+'&components=country:'+country_code+'&location_type=GEOMETRIC_CENTER&key='+key+'&sensor=false 

Also, when cycling through JSON, sometimes POSTCODE is not included in the first hierarchy of results, so be sure to iterate over the 2nd line if POSTCODE is omitted in the 1st.

Here is an example of looping an array:

 url = geocode_query; fetch(url) .then(res => res.json()) .then((out) => { result = JSON.parse(out); postcode = get_postcode(result); // HERE is Your Postcode do what you need with it }) .catch(err => { throw err }); function get_postcode(results){ city_data = results['results'][0]['address_components']; for(i=0;i<city_data.length;i++){ var cv = city_data[i]; if(typeof cv['types'][0] != 'undefined')){ if(cv['types'][0] === 'postal_code'){ city['postcode'] = cv['long_name']; }else if(cv['types'][0] === 'postal_town'){ city['place_name'] = cv['postal_town']; } } } if(typeof city == 'undefined'){ city_data = results['results'][1]['address_components']; for(i=0;i<city_data.length;i++){ var cv = city_data[i]; if(typeof cv['types'][0] != 'undefined')){ if(cv['types'][0] === 'postal_code'){ city['postcode'] = cv['long_name']; } } } } return city; } 

Enjoy it!

+1
source

I do this by making two calls.

  On the first call my query is: geocode('address=' .$cty. ',' .$st, $key); $cty = city name - $st = state abbreviation - $key is my api key - On the second call my query is: geocode('latlng=' .$lat. "," .$lng, $key); $lat = latitude from first call - $lng = longitude from first call --------- My function appears below. -------------------------------------- function geocode($query, $key){ global $lat, $lng, $zipcode, $city, $state; $url = 'https://maps.googleapis.com/maps/api/geocode/json?'.$query.'&key='.$key; $json_string = curlfun($url); // this uses CURL to access the url (false on fail) if($json_string){ $parsed_json = json_decode($json_string, true); // if ($parsed_json['status'] == "OK"){ $lat = $parsed_json['results'] [0] ['geometry'] ['location'] ['lat']; $lng = $parsed_json['results'] [0] ['geometry'] ['location'] ['lng']; foreach($parsed_json['results'] [0] ['address_components'] as $a){ if($a ['types'] [0] == 'postal_code') $zipcode = $a ['long_name']; if($a ['types'] [0] == 'locality') $city = $a ['long_name']; if($a ['types'] [0] == 'administrative_area_level_1') $state = $a ['short_name']; } } else return false; } else return false; if(!$city) return false; // if there is no city just return false. return true; } --------------------------------------------------- 

Global variables are available to the rest of the script after calling the function. The function returns false on failure or true on success. Appropriate error handling should be done in the main code.

0
source
 var res; // store response in res variable var add_array = res[0].address_components; //add_array = { "long_name" : "Clarkston", "short_name" : "Clarkston", "types" : [ "locality", "political" ] }, { "long_name" : "Oakland", "short_name" : "Oakland", "types" : [ "administrative_area_level_2", "political" ] }, { "long_name" : "Michigan", "short_name" : "MI", "types" : [ "administrative_area_level_1", "political" ] }, { "long_name" : "United States", "short_name" : "US", "types" : [ "country", "political" ] }, { "long_name" : "48346", "short_name" : "48346", "types" : [ "postal_code" ] } var add_array = add_array[add_array.length-1]; //add_array = { "long_name" : "48346", "short_name" : "48346", "types" : [ "postal_code" ] } var zip = add_array.long_name; //zip = 48346 
-1
source

Source: https://habr.com/ru/post/910654/


All Articles