65.9K
CodeProject 正在变化。 阅读更多。
Home

基于 jQuery 的 Ajax ASP.NET MVC Google Maps Web 应用

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.84/5 (84投票s)

2014 年 10 月 14 日

CPOL

3分钟阅读

viewsIcon

167842

downloadIcon

10487

基于 jQuery 的 Ajax ASP.NET MVC Google Maps Web 应用

目标

这里的目标是创建一个国家定位器,其中我们有一个 SQL Server 数据库,它有一个包含所有国家位置查找的表,以及它们相关的 Latitude Longitude。 因此,该表将填充以下数据

使用上述数据,我们将在 ASP.NET 中创建一个简单的单页 MVC Web 应用,该应用显示一个 Google 地图,并在地图上绘制这些位置。 将会有一个搜索条件框,允许用户过滤要显示的位置。 当他们键入内容时,应动态绘制与条件匹配的图钉。

一些规范

  • UI 必须是 ASP.NET MVC,并且应该在没有完整页面回发的情况下刷新,即,我们将使用基于 jQuery 的 Ajax 调用。
  • 数据格式将是我们需要传递给服务器的 JSON。
  • 数据访问技术将是 Entity Framework。
  • 编程语言将是 C#。
  • 如果搜索条件框为空,则显示所有位置,但不绘制任何国家/地区。
  • 如果为条件输入文本,则对位置执行类似查询。 例如,如果他们只输入单个字母“e”,则返回所有以“e”开头的位置。

我们将实现的目标

  1. 当搜索框中未输入任何内容时。

  2. 当我们搜索以“I”开头的国家/地区时。

实施步骤

步骤 1

让我们将实体数据模型添加到我们的 ASP.NET MVC 应用,即 GoogleMap

第二步

添加一个地图控制器并向其添加一个 index 操作,该操作将返回一个包含所有位置列表的视图。

步骤 3

让我们添加一个视图 Index 作为

它应该显示所有带有搜索框的位置,如下所示

步骤 4

让我们实现响应式搜索。 为此,我们需要从 nuget 添加 jQuery 和 Ajax 脚本文件,并将它们拖到视图 Index 上。

步骤 5

每当通过跟踪 keyup 事件在搜索文本框中输入字符时,我们需要进行基于 jQuery 的 Ajax 调用,并将这些字符发送到 Action search。

步骤 6

让我们实现 action Search,它应该显示以文本框中输入的 char 开头的国家/地区列表。

步骤 7

让我们渲染 Google 地图,为此,您需要添加带有密钥的 Google 地图 API 脚本文件,并创建 google.maps.Maps 对象,它将显示如下所示的地图

步骤 8

现在,我们将根据搜索结果绘制地图,使用一个 pinlball.png。 为此,我们需要为每个结果的 Lat Lng 创建 google.maps.LatLng 对象,并将其传递给 google.maps.Marker 对象以绘制该位置。 我们需要在 Ajax 调用成功函数的 foreach 循环中插入我们的代码。 并且应该按预期工作。

步骤 9

我需要在两种情况下清除绘制的位置,即每次我们进行新的搜索时,以及当搜索文本框为空时。 为此,我们需要跟踪数组中绘制的所有位置,并在我们进行 Ajax 调用之前以及搜索文本框为空时,从地图中清除这些位置。

第 10 步

完整的源代码如下所示

控制器源代码

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 视图源代码

@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>
© . All rights reserved.