Using Google Map in an ASP.NET MVC Application

Introduction

In this article, we will see how to show a Google Map in an ASP.NET MVC application. Basically in our application, we need to show the position of the user on the map. To display the user position we will use Google Map in our ASP.NET MVC web application. So let's proceed to show the Google Map in our MVC application.

Step 1. First, we have to register our Google Map API key so register your own key here and also download the Gmaps.dll from there.

Step 2. Now create your ASP.NET MVC application and add the controller in your application as well as add the view.

Step 3. Now add the reference to downloaded Gmaps.dll by right-clicking on the solution.

Step 4. Next, we have to register the tag prefix and import the namespace of G-map like below.

<%@ Register assembly="GMaps" namespace="Subgurim.Controles" tagprefix="cc1" %>
<%@ Import Namespace="Subgurim.Controles" %>

Step 5. Next, write the script with runat=server attribute in <head></head> section for containing Page_Load. We will show the map in the page_load event; write down the following code in the script to load the map by giving the city, state, and country information.

<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        SeeMap("Hyderabad", "Andhra Pradesh", "India");
    }
}
private void SeeMap(string _city, string _state, string _country)
{
    string fulladdress = string.Format("{0}.{1}.{2}.{3}", "Assembly", _city, _state, _country);
    //change your api key in web.confige file
    string skey = ConfigurationManager.AppSettings["googlemaps.subgurim.net"];
    GeoCode geocode;
    geocode = GMap1.getGeoCodeRequest(fulladdress);
    var glatlng = new Subgurim.Controles.GLatLng(geocode.Placemark.coordinates.lat, geocode.Placemark.coordinates.lng);
    GMap1.setCenter(glatlng, 16, Subgurim.Controles.GMapType.GTypes.Normal);
    var oMarker = new Subgurim.Controles.GMarker(glatlng);
    GMap1.addGMarker(oMarker);
}
</script>

In the above lines of code, we loaded the map by passing city, state, and country information. In the above code, we are loading the API key from the web. configure file so change your API key on the web. configure file.

Step 6. Next, put the Gmap control in the <body></body> section on your aspx page like below.

<cc1:GMap ID="GMap1" runat="server" Height="300px" Width="300px" />

Step 7. Now run your application and see the map.

Conclusion

In this easy way, we can show the map on our ASP.NET MVC view.


Similar Articles