google maps in a razor view

These days I was working on a ASP.NET MVC web application to show events on a map. I had to use Google Maps for that purpose. I looked around for a way to integrate these maps. Fortunately Google provides a JavaScript API, which was the best option for me to explore. Although you can use it without any key, but creating and using a key is a good practice. If you have one, Google provides you usage statistics, and can warn you on exceeding your limits. For creating a key you will have to launch Google API Console. After going through the initial reference documents, I was ready to try it in my own application.

I won’t go in detail how we will fetch data from database, and pass it on to our view, just the plain view, and how things are working on it. First we need to add reference of maps API. Then add a div element in your body, which will host the map. To show our initial map, we need to configure some options of this map, get the reference of div element where we want to show this map, and create instance of the map. That’s the simplest part of showing a map.




Let me elaborate it further.

First we picked a location where we want to center our map, we need latitude and longitude of that location. Next we need to configure our map, we can specify following options:

  • center: that would be latitude and longitude of a location on a map
  • zoom: initial zoom level of the map
  • mapTypeId: which type of map to display (we are using a road map). However following map types are supported
    • ROADMAP
    • SATELLITE
    • HYBRID
    • TERRAIN

Then we create a map object using the selected element and map options. All these efforts gives us the following.

razor.google.maps

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.