<img alt="" src="https://secure.leadforensics.com/150446.png " style="display:none;">
Go to top icon

How to Use Google Maps in ASP.net MVC Application

Kirti Bodekar Feb 19, 2015

Microsoft .Net Technology

Introduction

Before we jump into the integration bit, let me introduce the API Google Maps JavaScript API v3 that is used for the integration of Google Maps. This API is used when we want to customize Maps according to our requirement. We can draw Polygon, Polylines, have Click events etc. using this API.

To get started, we need a specific API key from Google. The Key is free and is required to complete this process.

To create your API key:

  1. Visit the APIs Console at https://code.google.com/apis/console and log in with your Google Account.
  2. Click the Services link from the left-hand menu.
  3. Activate the Google Maps JavaScript API v3 service.
  4. Click the API Access link from the left-hand menu. Your API key is available from the API Access page, in the Simple API Access section. Maps API applications use the Key for browser apps.

API applications

By default, a key can be used on any site.

Now the Google Maps are ready to be used in your MVC Application.

To use Google Maps in your MVC application, declare the following URLS in your Layout.cshtml:-

1.
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/themes/base/jquery-ui.css"
        rel="stylesheet" type="text/css" />
2.<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=drawing,geometry"></script>

Then include the styles in your head section:-

<style>

       #mapDiv img {
         max-width: none !important;
        }
</style>

The #map are the ids of div where you need to render this Google Map.

Now you need to render this Google Map on the click of a button along with drawing polygon in this Google Map. After drawing the polygon, you need to find the area of the polygon marked on the Google Maps.

For this, you need to have div to render Google Maps in CSHTML page. Let’s consider Index.cshtml and ViewMap.cshtml page. This ViewMap.cshtml is a partial view which gets loaded after clicking the show Maps button in Index.cshtml page.

So, you need to write a function in ViewMap.cshtml page to load the map dynamically on the click of a button in Index.cshtml page.

<div id="mapDiv" style="width: 600px; height: 500px"></div>

<button type="button" id="btnShowMaps"> Show  Map</button>
</div>

Then write a Jquery function on the click of a button to load the Google Maps in DIV.

$("#btnShowMaps").bind("click", function() {
      setTimeout(function () { initialize(); }, 1);

}

The Code below loads the Google Maps in div named as “mapDiv” using Javascript.

<script type="text/javascript">
        var Map;                  
        var DrawingManager;       
        var Field;                
        var InfoWindow;           
        var centerpointofMaps;            
        var marker = null;

        	 Below is Initialization function which sets up the map in the div.
           function initialize() {

             // assign map the options of zoom and give center points. 
            centerpointofMaps = new google.maps.LatLng(45, -90.00); 

            var mapOpt = {
            zoom: 12, 
            center: centerpoint, 
           mapTypeId: google.maps.MapTypeId.HYBRID
        };

	//initialize the object Map.

           Map = new google.maps.Map(
            document.getElementById("mapDiv"),
            mapOptions);

           InfoWindow = new google.maps.InfoWindow();

           // Add drawing tools in Map
                PolygonDrawingTools();
            }

Below is Initialization function which sets up the map in the div.

Place the marker image in the folder from where you can access the image and then give the relative location.

var image = new google.maps.MarkerImage(~/gmap-marker.png',
                                                    new google.maps.Size(91, 91),
                                                    new google.maps.Point(0,0),
                                                    new google.maps.Point(18, 42)
                                                    );
            var marker = new google.maps.Marker({
            position:centerpoint,
            map: Map,
            icon: image});

        }

The function below gives information about adding Drawing Tools in Google Maps.

       function PolygonDrawingTools () {

            DrawingManager = new google.maps.drawing.DrawingManager({
                drawingMode: null,
                drawingControl: true,
                drawingControlOptions: {
                    position: google.maps.ControlPosition.TOP_RIGHT,
                    drawingModes: [
                    google.maps.drawing.OverlayType.POLYGON
                ]
                },
                polygonOptions: {
                    draggable: true,
                    editable: true,
                    fillColor: '#cccccc',
                    fillOpacity: 0.5,
                    strokeColor: '#000000'
                }
            });

     //Set a Map.
            DrawingManager.setMap(Map);

            // when polygon drawing is complete, an event is raised by the map
            FieldDrawingListener();
        }

When a polygon is created with Drawing tools, an event is raised. This function catches that event and hides the drawing tool. It also adds custom properties to the polygon and generates a listener to listen to the click events on the created polygon.

   function FieldDrawingListener() {
            DrawingManager,
            'polygoncomplete',
            function (polygonval) {
                Field = polygonval;
                DrawingTools(false);
                PolygonEditable(false);
                FieldClickListener();
                FieldmouseOverListener();
            }
        );
        }

The function below describes the process of attaching an event listener to the polygon on a click event.

          function FieldClickListener() {
            google.maps.event.addListener(
            Field,
            'click',
            function (event) {
		// Write function over here.
            }
        	);
        }

The function below tells you how to attach an event listener to the polygon on mouseover event.

function FieldmouseOverListener() {
            google.maps.event.addListener(
            Field,
            'mouseover',
            function (event) {
           	// Write function over here.
            }
        );
        }

The function below tells you how to delete the polygon and show the drawing tools so that a new polygon can be created.

function DeleteField() {
            InfoWindow.close();
            Field.setMap(null);
            DrawingTools(true);
         }

	 The function below tells how to get the Coordinates of Polygon.
        function GetCoordinates(polygon) {
         var boundrange = new google.maps.LatLngBounds();
            var coordinatespoints = polygon.getPath().getArray();
var CordinatesVal;
             for (var ival = 0; ival < coordinatespoints.length; i++) {
                CordinatesVal += coordinatespoints[ival].lat() + ', '
                + coordinatespoints[ival].lng();
            }

            return CordinatesVal;
        }

</script>

From the code of Google Maps given above, you can customize your Google Maps. Following are the features included:-

  1. You can dynamically add a search box or text box which will search the location on the click of search button.

Map.controls[google.maps.ControlPosition.TOP_LEFT].push(TextBox);

  • We can mark the area on the Google Maps and then calculate the area of that marked map.

google.maps.geometry.spherical.computeArea(Field.getPath())

  • We can get Latitudes and Longitudes of all the area marked on Google Maps.

google.maps.geometry.spherical.computeArea(Field.getPath())

  • We can get Latitudes and Longitudes of all the area marked on Google Maps.

Below is a screen grab of the Map showing the pointer on the location searched in the text box.
Map showing the pointer on the location searched in the text box

Note - Google Maps can also be loaded in Iframe in the MVC application.

References: - https://developers.google.com/maps/documentation/javascript/tutorial

e-Zest is a leading digital innovation partner for enterprises and technology companies that utilizes emerging technologies for creating engaging customers experiences. Being a customer-focused and technology-driven company, it always helps clients in crafting holistic business value for their software development efforts. It offers software development and consulting services for cloud computing, enterprise mobility, big data and analytics, user experience and digital commerce.