MVC Google Maps HtmlHelper - Dynamic Maps

I've recently been looking for a MVC helper class for Google maps. I came across this well written MVC HtmlHelper for static Google maps. Unfortunately I was looking for a helper that was for the dynamic version of Google charts. I needed to be able to add markers on the maps with dynamic text and possibly even images.

Google Maps

So, a great way to re-use code in MVC 2 is the Htmlhelper class. I have also written about this before where I wrote a Google Charts Htmlhelper. For this example however, I also needed to take advantage of the great way that MVC combines with Javscript to return JSON data.

First, I wrote a method that would return my JSON data to the client side.

I wrote a small Javascript file that will handle the JSON and pass it on to Google and draw the map.

Incorporating this into a Html helper was pretty easy:

Now when you call the Html you simply need to do the following in your page:

<%= Html.DrawMap("your_api_key_goes_here","/Home/GetMarkers","550", "400")%>

The first parameter is the API key that you need when accessing Google maps, it's free and easy to sign up for one, just go to The second parameter is the location of the JSON service that we need to call to get the data (The name of the method that we wrote in the controller).Finally the third and fourth parameters are the width and height respectively.

This is how the map will look.


I have created a sample project that you can download, but you will need to get an API key in order for the map to display correctly. There is also a minified version of the Javascript included in the project that you might want to switch to.

Download Download