Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

jQuery Based Ajax ASP.NET MVC Google Maps Web App

0.00/5 (No votes)
3 Nov 2014 1  
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:

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.

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

Implementation Steps

Step 1

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

Step 2

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

Step 3

Let’s add a view Index as:

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

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.

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.

Step 6

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

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:

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.

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.

Step 10

The complete source code is given below:

Controller Source Code

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

@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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here