Google Geocode API with Powershell

I have a work requirement to look up zip codes based on incomplete addresses (street, city, state, etc) – this could be accomplished by going into Google Maps and plugging in the partial address which will then give you the completed address with the zip code. But what if you had a list of hundreds of incomplete addresses that you need the zip code for?

Below is a demonstration of how to leverage Google’s geocode API using Powershell to perform the zip code lookup.

First off, Google lets you make a handful of calls to their APIs for free, anything over that handful will require an API key. If you get an API key, it is free as long as you stay under a certain limit of calls made per day. If you go over that limit, then you will have to create a Google Developer account and pay for the service as you go. I went ahead by creating a free API key as I do not plan on making more than the limited calls per day. I suggest you look at the API limits and read their documentation as it is very informative and overall beneficial even if you do not end up creating an API key for yourself.

The API call works by using the following URL in your browser – this is Google’s example:
https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY

The result of the API call, if it is legitimate and well formed, will return output in JSON format. In Powershell, we have to convert this JSON format:

If you set the above Invoke-WebRequest (alias is wget) results to a variable, that variable will now hold the entire read-able json file in a format that can be manipulated by Powershell.

 

Great, now we know how to call the API, get data from it, convert the data to a useable format and extract the exact data we want from it – but how do we form the URL from just a plain address automatically?

I took the original address and added some symbols to be utilized as markers to easily split the strings and extract the values I want into separate variables. After that, I can use the individual variables and concatenate them into a single string to be used in the API call itself.

Now we can perform API calls on a single address but what about the earlier scenario where we have hundreds of addresses to lookup?

This version of the script works the same way as the first one, the only difference is that I have plugged in my hundreds of addresses in the required format into a text file. This script then reads that text file and does a “for each” loop performing the same logic from the first script on each line of address within the text file.

Please note, I had to “XXXX” out a lot of content due to security reasons, but the script itself is unaffected. Please comment if you have any questions.

Leave a Reply

Be the First to Comment!

avatar
  Subscribe  
Notify of