Coding Tips & Tricks


Home>MVC

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.

        public ActionResult GetMarkers()

        {

            // This would normally be our call to the Db,

            //else we could populate this

            // with some data as Ive done here.

            MarkerList markers = GetMarkersObjects();

           

            return Json(markers, JsonRequestBehavior.AllowGet);

        }

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:

        /// <summary>

        /// Draws the map.

        /// </summary>

        /// <param name="helper">The helper.</param>

        /// <param name="key">The key.</param>

        /// <param name="jsonUrl">The json URL.</param>

        /// <param name="mapWidth">Width of the map.</param>

        /// <param name="mapHeight">Height of the map.</param>

        /// <returns>The html of the map.</returns>

        public static string DrawMap(this HtmlHelper helper, string key, string jsonUrl, string mapWidth, string mapHeight)

        {

            StringBuilder mapHtml = new StringBuilder();

 

            // Google Maps API Link

            mapHtml.Append("<script src=\"http://maps.google.com/maps");

            mapHtml.Append("?file=api&amp;v=2&amp;sensor=false&amp;key=");

            mapHtml.Append(key);

            mapHtml.Append("\" type=\"text/javascript\"></script>");

 

            // Hidden value

            mapHtml.Append("<input type=\"hidden\" ");

            mapHtml.Append("id=\"MarkerUrl\" value=\"");

            mapHtml.Append(jsonUrl);

            mapHtml.Append("\" />");

 

            // Map Div

            mapHtml.Append("<div id=\"map\" style=\"width: ");

            mapHtml.Append(mapWidth);

            mapHtml.Append("px; height: ");

            mapHtml.Append(mapHeight);

            mapHtml.Append("px\"></div>");

 

            // Maps javascript file

            mapHtml.Append("<script type=\"text/javascript\" ");

            mapHtml.Append("src=\"/Content/GoogleMapping.js\"></script>");

 

            return mapHtml.ToString();

        }

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 http://code.google.com/apis/maps/signup.html. 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.

Map

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








Comments

PeterG - 5/10/2010
Thanks, I've been looking for something like this!

Rouven - 10/30/2010
Hey Dean, great sample. But i don't get another icon for the marker displayed. I tryed to give your Marker class a new property. I tried a couple auf property names according to the google API the name should be icon. But still the default icon is rendered. Do you have any idea how I could make it

mthuong - 12/9/2010
I want to view my point on google map when i click a button. How must i do?

Jenny - 12/9/2010
I want to reload googlemap with a new marker when i click button

Ahmet KACMAZ - 1/1/2011
I'm having a problem in this project. "Internet Explorer cache problem". How I can make?

SehaxX - 6/24/2011
Hi Dean, Great example! But I have a small problem, maybe you can help me out :D I used your example to create markers from DB, but my list returns without identifier markers. So I get this javascript error in Firebug: jsonData.markers is undefined

SehaxX - 6/24/2011
In the controller /home/GetMarkers: Your code:{"markers":[{"lat":"51.4109278","lng":"-0.2091921","html":"Some stuff to display in the\u003cbr\u003eFirst Info","label":"Marker"}]} My Code:[{"lat":"45.59929","lng":"8.951683","html":"i\u003cbr /\u003eMilano\u003cbr /\u003eSan Siro","label":"Italy"}]

Dean Hume - 6/24/2011
@SehaxX what is your markerlist object being set to? You need to check that the names match the JSON and the Javascript or it wont match up.

SehaxX - 6/24/2011
Thanks Dean, the problem was in the list object type. No it works perfect.

Dean Hume - 6/24/2011
@SehaxX No problem!

Hi - 2/7/2012
can anybody help me adding a label on moving google icon. I am using asp.net programing for icon plotting.I need some help in plotting the dynamic icon with a label and label should run on pageload rather than any mouse event.I have used the usual create marker javascript function but did not

ashu - 2/18/2012
Hi how can i add my own location?

Chandan - 1/11/2013
I am using VB with MVC3 instead of C#. Your downloaded sample is running very good but when I run the code getting error. var jsonData = eval('(' doc ')'); Here it is saying that jsonData is undefined. I go to the deep and find out that "GetMarkers()" is not firing. Why this is happened? Help


Add your comment

300 Characters left


Please fill this in to confirm that you are human