Click here to Skip to main content
15,881,380 members
Articles / Web Development / HTML

jQuery Based Ajax ASP.NET MVC Google Maps Web App

Rate me:
Please Sign up or sign in to vote.
4.84/5 (86 votes)
3 Nov 2014CPOL3 min read 161.8K   10.4K   69   56
jQuery Based Ajax ASP.NET MVC Google Maps Web App

Objective

The objective here is to create a country locator in which we have SQL server database with a single table which contains a lookup of locations of all the countries with their associated Latitude and Longitudes. So, the table is to be populated with the following data:

Image 1

Using the above data, we will be creating a simple one page MVC web app in ASP.NET which shows a Google map with these locations plotted. There will be a search criteria box that allows the user to filter which locations to show. As they type, the pins should be dynamically plotted that match the criteria.

Some Specifications

  • UI must be ASP.NET MVC and should get refreshed without full page post back, i.e., we will be using jQuery based Ajax call.
  • Data format will be JSON that we need to pass to the server.
  • Data access technology will be Entity Framework.
  • Programming language will be C#.
  • If the search criteria box is empty, then show all Locations but do not plot any country.
  • If text is entered for the criteria, then perform a like query on the locations. e.g. if they enter just the single letter 'e' then all locations which starts an 'e' are returned.

What We Will Achieve

  1. When nothing is entered in the search box.

    Image 2

  2. When we search for countries starting with “I”.

    Image 3

Implementation Steps

Step 1

Let’s add entity data model to our ASP.NET MVC app, i.e., GoogleMap.

Image 4

Step 2

Add a map controller and add an index action to it, which will return a view with list of all the locations.

Image 5

Step 3

Let’s add a view Index as:

Image 6

And it should display all the locations with search box as shown below:

Image 7

Step 4

Let us implement responsive search. To do so, we need to add jQuery and Ajax script files from nuget and drag them on view Index.

Image 8

Step 5

We need to make a jQuery based Ajax call whenever a character is entered in the search text box by tracking keyup event and send those characters to the Action search.

Image 9

Step 6

Let’s implement the action Search and it should display list of countries starting with the char entered in the text box.

Image 10

Image 11

Step 7

Let us render Google map and to do so, you need to add Google map API script file with key and create the object of google.maps.Maps, which will display the map as shown below:

Image 12

Image 13

Step 8

Now we will plot the map as per the search result with a pinlball.png. To do so, we need to create the object of google.maps.LatLng for each resulted Lat and Lng and pass it to the object of google.maps.Marker to plot that location. We need to plug our code in foreach loop of Ajax call success function. And should work as expected.

Image 14

Image 15

Step 9

I need to clear the plotted locations in two scenarios, i.e., every time we make a new search and whenever the search text box is empty. To do so, we need to keep track of all locations plotted in an array and clear those from map before we make an Ajax call and when the search textbox is empty.

Image 16

Step 10

The complete source code is given below:

Controller Source Code

C#
using GoogleMap.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace GoogleMap.Controllers
{
    public class MapController : Controller
    {
        // GET: Map
        public ActionResult Index()
        {
            GoogleMapEntities GE = new GoogleMapEntities();
            return View(GE.Locations.ToList());
        }

        [HttpPost]
        public ActionResult Search(string Location)
        {
            GoogleMapEntities GE = new GoogleMapEntities();
            var result = GE.Locations.Where(x => x.LocationName.StartsWith(Location)).ToList();
            return Json(result, JsonRequestBehavior.AllowGet);
        }
    }
}

Index View Source Code

JavaScript
@model IEnumerable<googlemap.models.location>

<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>

<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false"></script>

<script type="text/javascript">
    $(document).ready(function () {
        var gmarkers = [];
        var map;

        function initialize() {

            var mapProp = {
                center: new google.maps.LatLng(20.593684, 78.96288), //India Lat and Lon
                zoom: 2,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
        }

        google.maps.event.addDomListener(window, 'load', initialize);

       

        $("#txtSearch").keyup(function () {
            var x = $("#txtSearch").val();

            for (i = 0; i < gmarkers.length; i++) {
                gmarkers[i].setMap(null);
            }

 
                $.ajax({
                    type: "POST",
                    url: '@Url.Action("Search", "Map")', //"../Map/Search"
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify({ "Location": x }),
                    dataType: "json",
                    success: function (data) {
                        var table = "";
                        $.each(data, function (index, value) {
                            table += "";
                            var latlng = new google.maps.LatLng(value.Latitude, value.Longitude);
                            var marker = new google.maps.Marker({
                                position: latlng,
                                icon: "../pinkball.png",
                                map: map
                            });

                            gmarkers.push(marker);

                        });
                        table += "<table class="table"><tbody><tr>" + value.LocationName + "";
                        $("#myData").html(table);

                        if (x == "") {
                            for (j = 0; j < gmarkers.length; j++) {
                                gmarkers[j].setMap(null);
                            }
                        }
                    }
                });
        });
    });
</script>
<table>
	<tbody>
		<tr>
			<td valign="top">@Html.TextBox("txtSearch", null, new { @placeholder = 'Search A Country' })
			<div id="myData">@foreach (var item in Model) { }
			<table class="table">
				<tbody>
					<tr>
						<td>@item.LocationName</td>
					</tr>
				</tbody>
			</table>
			</div>
			</td>
			<td valign="top">
			<div id="googleMap" style="width:1000px;height:600px;"</div>
			</td>
		</tr>
	</tbody>
</table>

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Founder ManzoorTheTrainer.com
India India
Manzoor is a Microsoft Certified Trainer who has been working on MS .Net technologies for more than a decade. Apart from development he is also passionate about delivering training on various MS .Net technologies and he has 10+ years of experience as a software development teacher. He writes articles for code-project as well. His YouTube channel has 1 million hits. He is the founder of ManzoorTheTrainer portal.

"I focus on simplifying, complex concepts..." - ManzoorTheTrainer

Founder of www.ManzoorTheTrainer.com [Free .net video tutorials on MS SQL Server, Asp.Net, C#.Net, Ado.Net, Entity Framework, MVC, Web Services, Android]

Comments and Discussions

 
QuestionGoogle Map Events Pin
Member 130394378-Mar-17 21:48
Member 130394378-Mar-17 21:48 
QuestionUpdate to MVC Core coming :) Pin
longnights14-Dec-16 13:07
longnights14-Dec-16 13:07 
QuestionHow to display a window pop-up Pin
Kombassere9-Jun-16 8:59
Kombassere9-Jun-16 8:59 
QuestionHow to display a window pop-up Pin
Kombassere9-Jun-16 8:53
Kombassere9-Jun-16 8:53 
QuestionUsing multiple location in dynamically Pin
Member 1197698317-Mar-16 21:58
Member 1197698317-Mar-16 21:58 
QuestionASP.Net tutorials Pin
Member 1226689727-Feb-16 6:47
Member 1226689727-Feb-16 6:47 
AnswerRe: ASP.Net tutorials Pin
Mohd Manzoor Ahmed9-Oct-17 0:04
professionalMohd Manzoor Ahmed9-Oct-17 0:04 
GeneralMy vote of 5 Pin
Member 1024722124-Feb-16 3:01
Member 1024722124-Feb-16 3:01 
QuestionMessage Closed Pin
23-Oct-15 5:19
wikyyy12323-Oct-15 5:19 
AnswerRe: ajax code not work Pin
Mohd Manzoor Ahmed23-Oct-15 6:35
professionalMohd Manzoor Ahmed23-Oct-15 6:35 
QuestionWhat if no search? Pin
Member 1201460812-Oct-15 8:21
Member 1201460812-Oct-15 8:21 
QuestionThank U Pin
Member 1136793124-Jul-15 22:44
Member 1136793124-Jul-15 22:44 
AnswerRe: Thank U Pin
Mohd Manzoor Ahmed27-Jul-15 16:53
professionalMohd Manzoor Ahmed27-Jul-15 16:53 
AnswerRe: Thank U Pin
wikyyy12323-Oct-15 5:28
wikyyy12323-Oct-15 5:28 
QuestionAdd a Listening/Click Pop-Up Pin
Member 1017439731-May-15 10:08
Member 1017439731-May-15 10:08 
QuestionIE support? Pin
Himanshu Jain28-May-15 19:19
Himanshu Jain28-May-15 19:19 
QuestionInvert behaviour Pin
Laurentiu LAZAR17-Apr-15 9:44
Laurentiu LAZAR17-Apr-15 9:44 
QuestionGoogle map Multiple Location at a time Pin
Member(Jilby) 1102400722-Dec-14 0:36
Member(Jilby) 1102400722-Dec-14 0:36 
AnswerRe: Google map Multiple Location at a time Pin
Mohd Manzoor Ahmed1-Jan-15 5:49
professionalMohd Manzoor Ahmed1-Jan-15 5:49 
GeneralRe: Google map Multiple Location at a time Pin
Member(Jilby) 1102400716-Feb-15 20:01
Member(Jilby) 1102400716-Feb-15 20:01 
GeneralRe: Google map Multiple Location at a time Pin
Aarif Ansari24-Nov-15 20:40
Aarif Ansari24-Nov-15 20:40 
GeneralRe: Google map Multiple Location at a time Pin
Mohd Manzoor Ahmed24-Nov-15 22:25
professionalMohd Manzoor Ahmed24-Nov-15 22:25 
QuestionMultiple Location at a time Pin
Member(Jilby) 1102400722-Dec-14 0:35
Member(Jilby) 1102400722-Dec-14 0:35 
Questionvote 5 Pin
Member 196150521-Nov-14 5:44
Member 196150521-Nov-14 5:44 
GeneralMy vote of 5 Pin
Member 1064518821-Nov-14 5:22
Member 1064518821-Nov-14 5:22 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.