Creating County Overlays with Google Maps Javascript API

I am working with a client that wanted a feature on their website where users could find the nearest sales rep to their location. The client’s company have several sales reps that represent various counties in Southern California. I began working on using the awesome Google Map API to create such a tool, and it will be launched soon.

As I worked on the tool, I learned a lot, and I wanted to share some of my new-found knowledge with everyone. In the following post (including a video, yay!) I will show you how to create a county overlay on a Google Map.

The Video

You can watch a video of me explaining everything below. In it I explain things in more detail.

The Basics

To see the final product we are aiming for, click here.
To begin, we need to initialize the Maps API with the following:

<script src="http://maps.google.com/maps/api/js?sensor=true"></script>

The “?sensor=true” parameter tells the API whether it should try and take advantage of any GPS sensors that might exist on the device accessing the map. We won’t be using this function, but its not a bad thing to include for the future.

Next, we need to embed a map on our page. We can do this by making the following function and firing it using the body onload method.

function loadMap(){

	var myOptions = {
			zoom: 9,
			center: new google.maps.LatLng(34.0522,-118.2437),
			mapTypeId: google.maps.MapTypeId.TERRAIN
		};

	var map = new google.maps.Map(document.getElementById("map"), myOptions);

}

This code sets zoom, center, and type parameters for the map and then creates the map by targeting an element with an id of “map” (in this case we used a div).

Getting County Area Data

The Maps API has not function to automatically create overlays in the shape of state counties. It can, however, take a set of LatLng coordinates and create a polygonal overlay. After a little Googling. I came across the U.S. Census Bureau Cartographic Boundary Files. They give you nicely organized lists of coordinate areas of every county in America (and a ton of other boundary types, like school districts, voting areas, and zip codes). The only problem is that the data isn’t ready for the Maps API.

To convert it, I went through of series of steps involving find and replace, spreadsheet manipulation, and the terminal. It sounds confusing and long, but its still a pretty straightforward process. For the textual examples, I have used only a few datapoints to conserve space. Below is a flowchart of the steps:

Using the Data

Phew! Now we have the data in a usable form, it’s time to store it in our code. The best way to do this is to create an external file called data.js and input the data into it as a variable with the name rawData, like so:

var rawData =" 42.0038450000000,123.230762000000;42.0054460000000,123.192361000000;42.0080360000000,123.154908000000;";

Don’t forget to include this file in your page header. Next, we need to iterate through the data and create an array of LatLng objects. We will do this in a function called createOverlay():

function createOverlay(){

				var overlayCoords = new Array();

				var processedData = rawData.split(";");

				for (var i=0; i

This code splits the data into array elements by searching for semicolons. It then takes each element of the new array and splits it again into latitude and longitude by finding the comma. The coordinates are stored in a new google.maps.LatLng object and pushed onto an array called overlayCoords. This array is then parsed to a new google.maps.Polygon

object along with some other parameters. This object is returned out of the function.

Putting it All Together

Now we have our function for creating overlays, we can fire it by placing the following two lines of code in the loadMap function after the map is created.

var laCounty = createOverlay();
laCounty.setMap(map);

This code creates a variable called laCounty that is set equal to the overlay created by the createOverlay function. The variable is then placed on the page. The results look something like this:

Adding a Clear Function

v3 of the Google Maps API has not easy way to clear overlays on a map. This is somewhat of a pain, especially if you are going to display multiple county overlays in one session. The good news is there is a relatively simple workaround. Every time you place an overlay on the map, push it onto a special array to keep track. When you want to clear the map, iterate through the overlay array placing each element on the map as null (essentially deleting it). Finally clear the overlay array to start fresh. If it sounds confusing, watch the video as I explain it and show its use with a nice button.

Finishing Up

I hope this has been helpful for someone out there! If you would like to view a live example of this all in action, click here. Let me know in the comments if you have any questions or ideas on things you would like me to explain in the future!

10 Responses

  1. Nate the Great says:

    Very cool tutorial, gives me some good ideas for a similar project. One potential problem when you are parsing the data from the US census bureau. The data I got for my state (Wisconsin) did not have a “E+03″ for the first coodinate, it was a “E+02″ for both coods. So you’ll have to get creative on how to replace that one.

    • Elliott says:

      Hi Nate,

      I’m glad the tutorial gave you some good ideas! In regards to the E+03 issue, I suppose you could replace both E+02′s with commas, and then in Numbers or Excel remove the commas from one column (if it even shows up after being converted to a spreadsheet from CSV).

      Have a great day!

      Elliott

  2. Nate says:

    Hey Elliot, do you know what causes the random line (where you need to delete the first coordinate). There are some counties that still have this random line problem even though I’ve deleted the first coordinate (Ex. Hooker County Nebraska – 31091). Cheers!

    • Elliott says:

      Hi Nate,

      I only found through trial and error that deleting the first coordinate removed the ine so it could be that I got lucky with the counties I was drawing. You could try looking at the coordinates of where the line is occurring and delete the points that are nearby. Sorry I don’t have a great answer!

      • Keith says:

        Thanks for the very helpful tutorial.

        I’ve also found that stray lines may appear in IE due to an extraneous semicolon found at the end of the “rawdata” value (as in this tutorial). Also, I noticed that this approach does not work for extremely large counties (like those in “AK”), which I believe is due to a javascript field size limit (as applies to the “rawdata” field).

        A colleague told me that this may be accomplished more simply using Google KML. Have you investigated this approach at all?

  3. Anonymous says:

    Great video. I have used what you have shown and taken to next level to dynamically draw needed counties on demand. I do have one question, how do you determine is a given lat/long is wintin a county?

  4. al zorgraf says:

    thanks for the tutorial- it made my day actually:-) is it possible to make all of these “raw data” overlays cache in browser so users dont have to reload?

  5. dil says:

    Thanks Elliot.

    How do I loop through an array of counties making them separate polygon. Currently all the counties join together.

    Your help would be much appreciated.

    Thanks  

  6. Philip Housel says:

    Thanks for the great tutorial, I must have got lucky, the cat command worked without the double semicolons. One note, I had to use back slash rn not forward slash /r/n to make it work. Again thankyou, I really got a chuckle when you paused to find the closing script tag. I’d seen that and remembered all the times I forgot to close a tag.

Leave a Reply