Lookup City and State by Zip Google Geocode Api [closed]
Asked Answered
B

4

87

I basically want to retrieve a list of city and state within a zipcode. Is Google's Geocode API capable of doing so? I've tried looking into the documentation but found the information overwhelming.

Any help would be appreciated. If there is another method of accomplishing such task, please let me know.

Thanks

EDIT: I was able to retrieve the City and State through: http://maps.google.com/maps/geo?output=xml&q=14606 but is there a limitation against that?

Buckwheat answered 20/1, 2011 at 16:25 Comment(1)
You can use the HERE Maps Geocoding REST API. Create a project and get the REST credentials. Wait for 1 hour for them to go live (showed me an InvalidCredentials error at first) and then call e.g. geocoder.cit.api.here.com/6.2/geocode.json?PostalCode=2400&country=Denmark&app_id={APP_ID}&app_code={APP_CODE}&gen=9 (you can provide the address parts)Gratulate
F
117

Use the GeoCoding API

For example, to lookup zip 77379 use a request like this:

https://maps.googleapis.com/maps/api/geocode/json?address=77379&sensor=true&key=YOUR_GOOGLE_PLATFORM_API_KEY

Fugitive answered 20/1, 2011 at 16:35 Comment(21)
You mean sensor=false?Gilbert
Jason if I enter a postal code from another country Google returns all matching results around the world. Is there a parameter where I can set an ISO country code?Incommodity
look at the section on "Region Biasing" in the linked API docFugitive
"Note: the Geocoding API may only be used in conjunction with a Google map; geocoding results without displaying them on a map is prohibited."Inflame
An alternative is github.com/Loceo/loceo-jquery-pluginDecoupage
@Incommodity components=country:us for examplePopsicle
Unfortunately, Loceo is dead as of 2014-09-03Datcha
here is a simple API also, it returns city ,state and a GeoJson boundary representation of the zipcode(or multiple) queried.: api.reaperfire.com/reaperfire/rest/v1/public/…Lohman
@Gilbert sensor is not required anymoreMopes
@JerylCook how can I send country to it?Mopes
@Dejel It was when I wrote that four years ago. And if you are going to pass it for a zip code lookup, like in this answer, you should say false.Gilbert
@Dejel , mashape.com/vanitysoft/boundaries-io is the official entry point for the API, not its US state,city, and zipcodes right now.Lohman
@JerylCook thanks but it's for US address only. I am looking for something globalMopes
This is the first hit on google when googling "city zip code api", and and this is obviously not that :(Bevy
This doesnt work always. Say if your postal code is 00001, maps.googleapis.com/maps/api/geocode/…, will return an address with postal code 88030Traffic
You can restrict this to lookup only postal codes by setting the result_type param to postal_code. Here's a full example: maps.googleapis.com/maps/api/geocode/…Wingover
@KevinLeary result_type does not restrict to the postal code. Google's geocoder will mistake zip codes for street address numbers (try zip 89100). Instead the format to use is maps.googleapis.com/maps/api/geocode/… as documented here: developers.google.com/maps/documentation/geocoding/…Mew
How were you able to do this without a API key? The documentation states you have to use a API key, so I was under the impression I had to have one.Patman
doesnt return for 97703 zip code. what can be an alternativeAlmanac
@AndyRay That is only half correct. As per Google, you can display data that is not on a map but you must show the 'Powered By Google' logo near the data in the app. source: developers.google.com/maps/documentation/geocoding/policiesHypophysis
If you need to lookup a zip code for a unique country you can do it adding to the URL parameter this: &components=country:ES (for SPAIN in my case) ... for example: maps.googleapis.com/maps/api/geocode/…Malaya
A
56

I found a couple of ways to do this with web based APIs. I think the US Postal Service would be the most accurate, since Zip codes are their thing, but Ziptastic looks much easier.

Using the US Postal Service HTTP/XML API

According to this page on the US Postal Service website which documents their XML based web API, specifically Section 4.0 (page 22) of this PDF document, they have a URL where you can send an XML request containing a 5 digit Zip Code and they will respond with an XML document containing the corresponding City and State.

According to their documentation, here's what you would send:

http://SERVERNAME/ShippingAPITest.dll?API=CityStateLookup&XML=<CityStateLookupRequest%20USERID="xxxxxxx"><ZipCode ID= "0"><Zip5>90210</Zip5></ZipCode></CityStateLookupRequest>

And here's what you would receive back:

<?xml version="1.0"?> 
<CityStateLookupResponse> 
    <ZipCode ID="0"> 
        <Zip5>90210</Zip5> 
        <City>BEVERLY HILLS</City> 
        <State>CA</State> 
    </ZipCode> 
</CityStateLookupResponse>

USPS does require that you register with them before you can use the API, but, as far as I could tell, there is no charge for access. By the way, their API has some other features: you can do Address Standardization and Zip Code Lookup, as well as the whole suite of tracking, shipping, labels, etc.

Using the Ziptastic HTTP/JSON API (no longer supported)

Update: As of August 13, 2017, Ziptastic is now a paid API and can be found here

This is a pretty new service, but according to their documentation, it looks like all you need to do is send a GET request to http://ziptasticapi.com, like so:

GET http://ziptasticapi.com/48867

And they will return a JSON object along the lines of:

{"country": "US", "state": "MI", "city": "OWOSSO"}

Indeed, it works. You can test this from a command line by doing something like:

curl http://ziptasticapi.com/48867 
Adjure answered 24/4, 2012 at 6:44 Comment(15)
Major love for the Ziptastic recommendation. <3!Tifanie
US Postal Service will probably deny your request for access unless you are using their API for activities specifically related to mailing. At least, that's been my experience.Highkey
"Ziptastic" is convenient to useShadoof
Unfortunate that it doesn't provide proper capitalization though.Briard
how can I provide country to ziptastic?Mopes
This answer does NOT work with international postal codes. US based only. For a global product use google.Kileykilgore
@Highkey That's true: "The Address Validation APIs can be used in conjunction with USPS SHIPPING OR MAILING SERVICES ONLY."Mckown
Ziptastic is no longer supported. It should not be used anymore.Idolism
Thanks for the heads up @Vaindil. Updated the answer to reflect this.Adjure
it doesn't surprise me that the US post office uses an XML API.... lol....Castiron
Updated link for documentation of USPS- usps.com/business/web-tools-apis/…Babb
Doesn't look very "non-supported" to me getziptastic.com . That said, unless they have improved their API (which they may have), it will only return one city/state per zip code. This is quite incorrect if accuracy is important. Sometime zip codes even cross state lines, and, certainly often span more than one city.Schramm
@RationalRabbit: I submitted an update noting that Ziptastic is now a paid API.Adjure
Not working with UK zip code "HA88NP"Thurmond
FYI for UPSP: User agrees to use the USPS Web site, APIs and USPS data to facilitate USPS shipping transactions only.Inexactitude
S
18
function getCityState($zip, $blnUSA = true) {
    $url = "http://maps.googleapis.com/maps/api/geocode/json?address=" . $zip . "&sensor=true";

    $address_info = file_get_contents($url);
    $json = json_decode($address_info);
    $city = "";
    $state = "";
    $country = "";
    if (count($json->results) > 0) {
        //break up the components
        $arrComponents = $json->results[0]->address_components;

        foreach($arrComponents as $index=>$component) {
            $type = $component->types[0];

            if ($city == "" && ($type == "sublocality_level_1" || $type == "locality") ) {
                $city = trim($component->short_name);
            }
            if ($state == "" && $type=="administrative_area_level_1") {
                $state = trim($component->short_name);
            }
            if ($country == "" && $type=="country") {
                $country = trim($component->short_name);

                if ($blnUSA && $country!="US") {
                    $city = "";
                    $state = "";
                    break;
                }
            }
            if ($city != "" && $state != "" && $country != "") {
                //we're done
                break;
            }
        }
    }
    $arrReturn = array("city"=>$city, "state"=>$state, "country"=>$country);

    die(json_encode($arrReturn));
}
Sharyl answered 8/5, 2015 at 20:59 Comment(1)
Part of your code helped me a little bit, Thanks a lot :)Thurmond
A
6

couple of months back, I had the same requirement for one of my projects. I searched a bit for it and found out the following solution. This is not the only solution but I found it to one of the simpler one.

Use the webservice at http://www.webservicex.net/uszip.asmx.
Specifically GetInfoByZIP() method.

You will be able to query by any zipcode (ex: 40220) and you will have a response back as the following...

<?xml version="1.0" encoding="UTF-8"?>
 <NewDataSet>
  <Table>
   <CITY>Louisville</CITY> 
   <STATE>KY</STATE> 
   <ZIP>40220</ZIP> 
   <AREA_CODE>502</AREA_CODE> 
   <TIME_ZONE>E</TIME_ZONE> 
  </Table> 
</NewDataSet>

Hope this helps...

Arvillaarvin answered 16/7, 2012 at 14:44 Comment(1)
URL doesn't work now!Shechem

© 2022 - 2024 — McMap. All rights reserved.