Google 地图 API是通过 JavaScript 将 Google 地图嵌入到网页中的。在这里简单介绍一下Google Maps的用法,以及同数据库的交互。
1.为了描述一个地点,需要创建一个类Locate,描述地点的经度纬度以及其他信息,根据需要可以添加其他属性。
public class Locate
{
public double Lat { get; set; }
public double Lng { get; set; }
public string Infomation { get; set; }
}
2.新建一个一般处理程序,用来处理前端的AJAX请求。
using System.Collections.Generic;
using System.Web;
using System.Web.Script.Serialization;
namespace GoogleMap
{
/// <summary>
/// LocateHandler 的摘要说明
/// </summary>
public class LocateHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
//如果需要从数据库读取这些信息,将下面这段代码替换一下
//把从数据库读取到的信息存入这个链表
List<Locate> locateList = new List<Locate>
{
new Locate { Lng = 115.41666, Lat = 41.050000 ,Infomation = "北京" },
new Locate { Lng = 120.85666, Lat = 30.666667 ,Infomation ="上海" },
new Locate { Lng = 113.27599, Lat = 23.117055 ,Infomation = "广州" }
};
//--------------------------------------------------
JavaScriptSerializer jss = new JavaScriptSerializer();
context.Response.Write(jss.Serialize(locateList));
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
3.新建一个HTML文档,然后调用Google Maps API。
<!DOCTYPE html>
<html>
<head>
<title>GoogleMap</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0px; padding: 0px }
#map_canvas { height: 100% }
</style>
<!--为了更方便地使用AJAX与服务器端交互,需要引入jQuery插件,下载地址:http://jquery.com/ -->
<script src="jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map;
var markersArray = [];
function initialize() {
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(41.050000, 115.41666),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
//注意下面这个一般处理程序(ashx)的名字和路径
$.post("LocateHandler.ashx", {
}, function (data, status) {
$.each($.parseJSON(data), function () {
addMarker(new google.maps.LatLng(this.Lat, this.Lng));
});
});
}
function addMarker(location) {
marker = new google.maps.Marker({
position: location,
map: map
});
markersArray.push(marker);
}
</script>
</head>
<body οnlοad="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>