Google Maps In MVC

Introduction

I was investigating using Google Maps in a web-application a while back and couldn't find a clear example that showed how to do it with MVC. Hopefully, this article fills that gap! Technologies used include MS C# MVC 4, jQuery, and of course, the Google Maps API.

Background

There were some "gotchas" I encountered while putting this together. The first (at least for me) is that, using a jQuery selector to link my div that would contain the Google map didn't work. I had to specifically use the JavaScript document.getelementById call. The second was sizing. Using the default size (which was teeny weenie) wasn't cutting it for me, so I increased width/height. Turns out, the Google Map didn't like that too much. After a bit of digging, I found a post that said to create a quick in-page style that set the max-width to "none" ... then it worked.

Using the code

Create a new MVC 4 project - this will include by default, appropriate links to jQuery and other supporting files you will need to run this tutorial.

All of the work, we are doing, is in the "Index view" - so go to that file and clean out any HTML etc., you don't need.

Add in a script ref to the Google Maps API at the top of the file.

 

  1. <script src="http://maps.google.com/maps/api/js?sensor=true" type="text/javascript"></script>   
Somewhere near that (or in an external stylesheet if you wish), add in this tweak to ensure the map and its controls size correctly.
  1. <style> #map_canvas img{max-width:none} </style>   
Here is another piece of CSS I put in - it is to style the popup infoWindow (optional) when someone clicks on a map-marker.
  1. <style>    
  2.     .infoDiv {    
  3.     height: 200px;        
  4.     width: 300px;     
  5.     -webkit-user-select: none;     
  6.     background-color: white;     
  7. }  </style>    
Before we drop in the script-code itself, we need to create a razor "SECTION" to surround the code. The reason for this is to let MVC manage the placement of the script within the output HTML file. This is important to ensure that things are loaded in the correct order.

If you look in the View folder, you will see a folder called "Shared" - in here is "_Layout.cshtml". This is the parent wrapper for the Index View page. At the bottom, you will notice these two lines.
  1. @Scripts.Render("~/bundles/jquery")     
  2. @RenderSection("scripts", required: false)     
This tells the razor engine "render/load all the jQuery files". Then once that is done, output any section marked as "scripts".

Let's go back to our view index page and add a section wrapper.
  1. @section scripts {     
  2. <section class="scripts">      
  3.    <script type="text/javascript">    
  4. // our code will go in here...    
  5.    </script>   
Now, the code that makes the magic happen.
  1. <!-- This code tells the browser to execute the "Initialize" method     
  2.          only when the complete document model has been loaded. -->    
  3. $(document).ready(function () {    
  4.     Initialize();     
  5. });     
Most will already know that the above is jQuery code that tells the browser only to execute the methodInitialize once the entire document model has been loaded. This ensures JavaScript does not try to trigger or access an object that has not yet been created.

Initialize is the main method that does all of the work.
  1. function Initialize() {   
Google has tweaked their interface somewhat - this tells the API to use that new UI.
  1. google.maps.visualRefresh = true;    
  2. var Liverpool = new google.maps.LatLng(53.408841, -2.981397);    
These are options that set the initial zoom level, where the map is centered globally to start, and the type of map to show.
  1. var mapOptions = {    
  2.     zoom: 14,    
  3.     center: Liverpool,    
  4.     mapTypeId: google.maps.MapTypeId.G_NORMAL_MAP    
  5. };    
This makes the div with id map_canvas a Google map.
  1. var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);  
This shows adding a simple pin "marker" - this happens to be the Tate Gallery in Liverpool!
  1. var myLatlng = new google.maps.LatLng(53.40091, -2.994464);    
  2. var marker = new google.maps.Marker({    
  3.     position: myLatlng,    
  4.     map: map,    
  5.     title: 'Tate Gallery'    
  6. });    
You can make markers different colors... Google it up!
  1. marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png')    
A sample list of JSON encoded data of places to visit in Liverpool, UK. You can either make up a JSON list server side, or call it from a Controller, using JSONResult.
  1. var data = [    
  2.   { "Id": 1, "PlaceName""Liverpool Museum",     
  3.     "OpeningHours":"9-5, M-F","GeoLong""53.410146",     
  4.     "GeoLat""-2.979919" },    
  5.   { "Id": 2, "PlaceName""Merseyside Maritime Museum ",     
  6.     "OpeningHours""9-1,2-5, M-F""GeoLong":     
  7.     "53.401217""GeoLat""-2.993052" },    
  8.   { "Id": 3, "PlaceName""Walker Art Gallery",     
  9.     "OpeningHours""9-7, M-F""GeoLong":     
  10.     "53.409839""GeoLat""-2.979447" },    
  11.   { "Id": 4, "PlaceName""National Conservation Centre",     
  12.     "OpeningHours""10-6, M-F""GeoLong":     
  13.     "53.407511""GeoLat""-2.984683" }    
  14. ];    
Using the jQuery each selector to iterate through the JSON list and drop marker pins.
  1. $.each(data, function (i, item) {    
  2.             var marker = new google.maps.Marker({    
  3.     'position'new google.maps.LatLng(item.GeoLong, item.GeoLat),    
  4.     'map': map,    
  5.     'title': item.PlaceName    
  6. });   
Make the marker-pin blue!
  1. marker.setIcon('http://maps.google.com/mapfiles/ms/icons/blue-dot.png')   
Put in some information about each JSON object - in this case, the opening hours.
  1. var infowindow = new google.maps.InfoWindow({    
  2.     content: "<div class='infoDiv'><h2>" +     
  3.       item.PlaceName + "</h2>" + "<div><h4>Opening hours: " +     
  4.       item.OpeningHours + "</h4></div></div>"    
  5. });    
(wow, I'm getting excited here, lots of fun!)

Finally, hook up an OnClick listener to the map so it pops up an info-window when the marker-pin is clicked!
  1. google.maps.event.addListener(marker, 'click'function () {    
  2.             infowindow.open(map, marker);    
  3.         });    
  4.     })    
  5. }   
And that's all there is to it! ... Press F9 to run. Nothing more to see here. Move along ! Opening hours on the map :)



Happy Mapping!

 

Up Next
    Ebook Download
    View all
    Learn
    View all