最近开发过程中涉及到了谷歌地图,在网上找了很多资料这才实现了多功能的谷歌地图开发应用:
下载地址是:GoogleMapAPIV3.zip
使用离线版本后,只需要加载mapapi.js这个文件,示例如下:
前台js:
<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Register Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
Namespace="System.Web.UI" TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"/>
<title>卫星地图</title>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css"/>
<script src="../../../Common/ExtJs/Js/ext-base.js" type="text/javascript"></script>
<script src="../../../Common/ExtJs/Js/ext-all.js" type="text/javascript"></script>
<link type="text/css" rel="Stylesheet" href="../../../Common/ExtJs/Css/ext-all.css"/>
<script type ="text/javascript" src="../../../Common/ExtJs/ux/Js/App.js"></script>
<script type="text/javascript" src="Js/jquery_1.7.js"></script>
<script type="text/javascript" src="../../../Common/Js/Utility/GlobalFunction.js"></script>
<link href="css/css.css" rel="stylesheet" type="text/css"/>
<%--在线调用谷歌地图接口--%>
<%--<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&language=zh-CN"></script>--%>
<%--离线调用谷歌地图接口--%>
<script type="text/javascript" src="mapapi.js"></script>
<!--* ROADMAP - 显示(默认的)2D地图
* SATELLITE - 显示卫星地图
* HYBRID - 在卫星地图上显示地名和交通线路
* TERRAIN - 在2D地图上显示地形图
-->
<script type="text/javascript">
var map; //定义地图(全局变量);
var markers=[]; //定义地图中标注数组(全局变量);
var windowContent=[]; //定义标注要显示的信息浮窗数组(全局变量);
var MinZoomLevel=10; //定义地图缩放最小级别;
var MaxZoomLevel=13; //最大级别;
var bounds=new google.maps.LatLngBounds(); //用于地图显示范围;
var latLngs; //定义坐标变量,用于存放多个坐标;
var icons; //定义坐标气泡变量,用于存放图片路劲;
var titles; //定义浮窗标题变量,用于存放标题;
var contents; //定义浮窗中显示的内容;
var info; //定义两个浮窗变量,用于打开第二个浮窗的时候,关闭前一个浮窗。
var info2;
var MarkerMethod=null; //定义两个变量用于调用全局方法;
var attachMessage=null;
//顶部菜单展开按钮效果:
$(function(){
$('.share > a').click(function(){
var xxid = $('.share').attr("id");
if(xxid == 'thisid'){
$('.share').animate({left:0},800);
$('.share').attr('id','thisida');
$('#map_canvas').animate({left:222,width:'-=222px'},800);//地图水平向右缩放;
}
else{
$('.share').animate({left:-222},800);
$('.share').attr('id','thisid');
$('#map_canvas').animate({left:0,width:'+=222px'},800);////地图水平向左缩放;
}
});
});
var parm=UrlParm.parm('code');//获取页面传递的参数;
function check(pageIndex){
Ext.Ajax.request({
url:"ditu.ashx",
params:{method: "GetLeftListInfo",
name:document.getElementById("searchContent").value,
pageIndex:pageIndex,
code:parm
},
method: "POST",
success: function (response) {
var json = response.responseText;
if (json!="") {
$("#ajaxdiv").empty();
$("#ajaxdiv").append(json); //将后台返回的html填充到指定的div中;
}
else {
$("#ajaxdiv").empty();
}
},
failure:function(){
App.setAlert('系统提示','请求失败!');
}
});
}
//初始化卫星地图:
function initialize() {
markers=[]; //用于每次调用此方法时候,清空之前存放的标注对象,及浮窗对象。
windowContent=[];
var myLatLng = new google.maps.LatLng(28.674425,115.90913699999998);//中国江西宜春奉新县
var myOptions = {
zoom: MinZoomLevel, //缩放倍数;
center: myLatLng, //地址坐标;
zoomControl:true, //可启用、停用缩放控件;
panControl:true, //可启用、停用平移控件;
rotateControl:false, //可决定显示、不显示用于控制45°图像方向的旋转控件
scaleControl: true, //比例尺 ;
mapTypeId: google.maps.MapTypeId.HYBRID, //默认地图类型:2D地图模式,上面注释;
mapTypeControl: true, //是否允许在右上角出现"地图类型"之间切换;
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,//DROPDOWN_MENU
position: google.maps.ControlPosition.TOP_RIGHT,
mapTypeIds: [google.maps.MapTypeId.ROADMAP,google.maps.MapTypeId.TERRAIN,google.maps.MapTypeId.HYBRID,google.maps.MapTypeId.SATELLITE]
}
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
map.setTilt(0);
//控制缩放级别:最小值和最大值
google.maps.event.addListener(map, 'zoom_changed',function() {
if (map.getZoom() < MinZoomLevel){
map.setZoom(MinZoomLevel);
}
if(map.getZoom()>MaxZoomLevel){
map.setZoom(MaxZoomLevel);
}
});
Ext.Ajax.request({
url:"ditu.ashx",
params:{method: "GetMarkerInfo",
name:document.getElementById("searchContent").value,
pageIndex:0,
code:parm
},
method: "POST",
success: function (response) {
var json = Ext.decode(response.responseText);
if (json.success == "OK") {
latLngs=[];
icons=[];
titles=[];
contents=[];
$("#type").html(json.MapInfo[0].TypeName);
for(var i=0;i<json.MapInfo.length;i++){
var contentString = '<div id="content">'+
'<div style="font-size:9pt;"><span style="color:green;">企业名称:'+json.MapInfo[i].SubTypeName+'</span>'+
'<br><span>地址:'+json.MapInfo[i].SubType_Y+'</span><br><span>联系电话:'+json.MapInfo[i].SubType_X+'</span><br><span>详情:********</span></div></div>';
latLngs.push(new google.maps.LatLng(json.MapInfo[i].SubType_X,json.MapInfo[i].SubType_Y));
icons.push(json.MapInfo[i].ImageUrl);
titles.push(json.MapInfo[i].SubTypeName);
contents.push(contentString);
bounds.extend(new google.maps.LatLng(json.MapInfo[i].SubType_X,json.MapInfo[i].SubType_Y));
}
//地图图标标注:
MarkerMethod(latLngs,icons,titles,contents);
//控制地图的显示范围:
MapRangeMethod(bounds);
check(0);
}
else {
}
},
failure:function(){
}
});
//地图标注:
MarkerMethod=function(latLngs,icons,titles,contents){
for(var i=0;i<latLngs.length;i++){
var marker= new google.maps.Marker({
map: map,
position:latLngs[i],
icon:icons[i],
title:titles[i]
});
markers.push(marker);
//添加监听事件:当点击地点坐标的时候,打开地图上的标记内容;
attachMessage(marker,contents[i]);
}
}
//地图标注弹出框:
attachMessage=function(marker,content){
//弹出信息框:注意这里的窗体是单独定义;
var infowindow=new google.maps.InfoWindow({
maxWidth:200, //定义点击图标显示方框尺寸;
content:content //方框中的信息;
});
//点击标注显示该标注的详细信息:
google.maps.event.addListener(marker, 'click', function(){
if(info!=null){
info.close(); //当点击完左侧栏中标题后,再点击地图中标注,关闭之前打开过的窗体;
}
if(windowContent.length>0){
for(var i=0;i<windowContent.length;i++){
windowContent[i].close();
}
}
infowindow.open(map,marker);
});
windowContent.push(infowindow);
// //添加监听事件:当鼠标移动到地点坐标的时候,打开地图上的标记内容;
// google.maps.event.addListener(marker,'mouseover',function(){
// infowindow.open(map,marker);
// });
}
//控制显示范围:
function MapRangeMethod(bounds){
// google.maps.event.addListener(map, 'drag', function(){//鼠标拖拽地图事件:dragstart、drag、dragend;
// checkMapBounds(bounds);
// });
google.maps.event.addListener(map, 'bounds_changed', function(){//地图移动事件:bounds_changed;
checkMapBounds(bounds);
});
}
function checkMapBounds(bounds){
if(bounds.contains(map.getCenter())){
return;
}
var center = map.getCenter();
var centerX = center.lng();
var centerY = center.lat();
var maxX = bounds.getNorthEast().lng();
var maxY = bounds.getNorthEast().lat();
var minX = bounds.getSouthWest().lng();
var minY = bounds.getSouthWest().lat();
if(centerX < minX) { centerX = minX; }
if(centerX > maxX) { centerX = maxX; }
if(centerY < minY) { centerY = minY; }
if(centerY > maxY) { centerY = maxY; }
map.panTo(new google.maps.LatLng(centerY, centerX));
}
}
//这里是针对左侧栏点击标题定位到地图中的标注,并显示窗体;
var contentString;
function SearchMarker(x,y,icon,title){
contentString='<div id="content">'+
'<div style="font-size:9pt;"><span style="color:green;">企业名称:'+title+'</span>'+
'<br><span>地址:'+y+'</span><br><span>联系电话:'+x+'</span><br><span>详情:********</span></div></div>';
info2=info; //将之前生成的窗体赋值给变量infoWindow2;
if(info2!=null){
info2.close(); //关闭之前打开过的窗体;
}
for(var i=0;i<markers.length;i++){
windowContent[i].close();
}
var myLatLng = new google.maps.LatLng(x,y);//后台传递(纬度、经度)寻找标注;
map.setZoom(10);
map.setCenter(myLatLng);
for(var i=0;i<markers.length;i++){
if(markers[i].position.jb==myLatLng.jb&&markers[i].title==title){
info=new google.maps.InfoWindow({
maxWidth:200, //定义点击图标显示方框尺寸;
content:contentString //方框中的信息;
});
info.open(map,markers[i]);
windowContent.push(info);
}
}
}
</script>
</head>
<body onload="initialize()">
<div class="share" id="thisid" style="width:17%;height:100%;position:absolute;top:0%;left:-220px;margin-top:0px;background:#fff; border-color:#000;border-width:0px; z-index:9999;">
<a style="display:block;position:absolute;top:10px;left:230px;right:0px;background:url(../images/top_icon.jpg)" href="#"><img src="Images/top_icon.jpg" width="10px" /></a>
<%--地图左侧的信息栏目--%>
<div class="listbox" >
<%--信息栏目第一行:工业、政策法规;--%>
<div class="tabI">
<ul>
<li id="type" class="hover" style="font:normal 15px 微软雅黑, 宋体, Arial, Helvetica, sans-serif;float:left;"></li>
<li style="font:normal 15px 微软雅黑, 宋体, Arial, Helvetica, sans-serif;float:left;">政策法规</li>
</ul>
</div>
<%--信息栏目第二行:查询地址;--%>
<div class="sou">
<div class="sou_input">
<input type="text" id="searchContent"/>
</div>
<div class="sou_an">
<input type="button" id="Button1" onclick="javascript:initialize();check(0)" />
</div>
</div>
<%--信息栏目第三行:主要信息内容;--%>
<div class="mian_text">
<div id="ajaxdiv"></div>
</div>
</div>
</div>
<%--右侧地图部分--%>
<div class="mapContent">
<div id="map_canvas" class="mapDiv"></div>
</div>
</body>
</html>
css样式:
/* CSS Document */
html{overflow:hidden}
*{margin:0;padding:0;}
body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,legend,input,textarea,button,p,blockquote,th,td{margin:0;padding:0}
fieldset, img {border:0}
address, caption, cite, code, dfn, em, th, var, b, i, s {font-style:normal;font-weight:normal}
ul, li {list-style:none}
caption, th {text-align:left}
h1, h2, h3, h4, h5, h6 {font-size:100%}
q:before, q:after {content:''}
input, textarea, select, button {font-family:inherit;font-size:inherit;font-weight:inherit;font-size:100%}
legend {color:#000}
input[type=search] {-webkit-appearance:none}
a img, a span, a strong, a s {cursor:pointer}
body, button, select, textarea, input, label, option, fieldset, legend {font:normal 12px/14px 微软雅黑, 宋体, Arial, Helvetica, sans-serif;}
button {white-space:nowrap;overflow:visible}
a {color:#898989;text-decoration:none}
a:hover {text-decoration:underline;color:#870000;cursor:pointer}
a:focus {outline:none}
.cup{cursor:pointer;}
.clear{clear:both;}
.xkbg{background:url(../images/nav_le.png) repeat-y 103px top;}
.lefttabI{width:200px;line-height:18px;border:0px solid #ececec;margin:0 1px; margin-left:6px; margin-top:20px;}
.lefttabI li{float:left;width:51px;text-align:center;cursor:pointer;font:normal 12px 微软雅黑, 宋体, Arial, Helvetica, sans-serif; height:51px; margin-left:8px;margin-top:15px;}
/*=======main=======*/
.listbox{width:100%;height:100%;border:0px solid #76777b;}
.listbox span.zkgb{width:24px;height:18px;display:block;position:absolute;right:3px;top:3px;cursor:pointer;}
.listbox h3{height:24px;font-size:12px;color:#444444;padding-left:10px;line-height:24px;}
.listbox h3 span{color:#ff9f0d;}
.tabI{width:216px;height:18px;line-height:18px;border:1px solid #ececec;margin:0 1px;}
.tabI li{float:left;width:108px;text-align:center;cursor:pointer;font:normal 12px 微软雅黑, 宋体, Arial, Helvetica, sans-serif;}
.tabI li.hover{background:url(../images/nv_bg.jpg) repeat-x;color:#fff;font:normal 12px 微软雅黑, 宋体, Arial, Helvetica, sans-serif;}
.sou{width:216px;height:18px;border:1px solid #ececec;background:#fafafa;margin:0 1px;margin-top:6px;}
.sou_input{line-height:18px;height:18px;width:157px;border-right:1px solid #ececec;float:left;}
.sou .sou_input input{width:151px;height:18px;line-height:18px;border:0;margin-top:0px;padding:0 3px;}
.sou .sou_an{width:58px;float:left;height:18px;line-height:18px;}
.sou .sou_an input{width:58px;height:18px;border:0;background:url(../images/chaxuen.jpg) no-repeat;cursor:pointer;}
.mian_text{width:100%;height:100%;overflow:hidden;position:absolute}
.mian_text a{color:#444444;}
.mian_text a dl{margin-top:10px;overflow:hidden;line-height:5px;width:220px;height:90px;}
.mian_text a dl dt{width:17px;float:left;height:45px;margin-right:7px;padding-top:2px;margin-left:10px;display:inline;}
.mian_text a dl dd{width:180px;height:70px;float:left;}
.mian_text a dl dd h4{color:#ffa630;font-size:12px;font-weight:normal;}
.fy{width:220px;height:30px;margin-top:10px;line-height:10px;text-align:center; font-weight:bold;}
.fy a:active { text-decoration: underline}
/*=======left=======*/
/*卫星地图的div样式:*/
/*
去除地图中信息浮窗阴影,
否则将会出现白色虚框(离线地图情况下);
如果是在线地图,则可以不需要此样式;
缺点:缩放标尺也不见了。
*/
div.gmnoprint div img
{
display: none;
}
/*谷歌地图样式*/
.mapDiv
{
height:100%;
width:100%;
margin-left:28px;
margin-right:0px;
position:absolute;
}
后台cs:
public class DiTuHandler : HttpHandlerBase
{
int Count = 0;
private IIndustrialMapService mapService = ServiceContainer.GetService<IIndustrialMapService>();
public override void ProcRequest(string method)
{
switch (method)
{
case "GetMarkerInfo":
GetMarkerInfo();
break;
case "GetLeftListInfo":
GetLeftListInfo();
break;
}
}
/// <summary>
/// 获取左侧列表信息:
/// industName:搜索关键字;
/// pageIndex:当前页号;
/// </summary>
private void GetLeftListInfo()
{
string subType = context.Request["name"].ToString();
int pageIndex = Convert.ToInt32(context.Request["pageIndex"]) * 5;
string code = context.Request["code"].ToString();
StringBuilder sbPage = new StringBuilder();
StringBuilder sbList = new StringBuilder();
DataTable dt = mapService.SearchMap(subType, pageIndex, 5, code, out Count).Tables[0];
if (Count > 26)
{
for (int i = pageIndex; i < dt.Rows.Count + pageIndex; i++)
{
sbList.Append(
"<a href=\"javascript:void(0);\" onclick=\"SearchMarker("
+ dt.Rows[i - pageIndex]["SubType_X"].ToString() + ","
+ dt.Rows[i - pageIndex]["SubType_Y"].ToString() + ","
+ "'Images/" + i.ToString() + ".png'" + ",'"
+ dt.Rows[i - pageIndex]["SubTypeName"].ToString() +
"')\" style=\"font-size:12px;\"><dl><dt>" + (i + 1) + "</dt><dd style=\"font:normal 14px 微软雅黑, 宋体, Arial, Helvetica, sans-serif;float:left;\"><h4>"
+ dt.Rows[i - pageIndex]["SubTypeName"].ToString()
+ "</h4><p>纬度:"
+ dt.Rows[i - pageIndex]["SubType_X"].ToString()
+ "<br>经度:" + dt.Rows[i - pageIndex]["SubType_Y"].ToString()
+ "</p></dd></dl></a>");
}
}
else
{
for (int i = pageIndex; i < dt.Rows.Count + pageIndex; i++)
{
//sbList.Append("<a href=\"javascript:SearchMarker(28.688423,115.10049099999999,Images/0.png,林业资源)\">"+ dt.Rows[i - pageIndex]["SubTypeName"].ToString() + "纬度:" + dt.Rows[i - pageIndex]["SubType_X"].ToString() + "<br>经度:" + dt.Rows[i - pageIndex]["SubType_Y"].ToString() + "</a>");
sbList.Append(
"<a href=\"javascript:void(0);\" onclick=\"SearchMarker("
+ dt.Rows[i - pageIndex]["SubType_X"].ToString() + ","
+ dt.Rows[i - pageIndex]["SubType_Y"].ToString() + ","
+ "'Images/" + i.ToString() + ".png'" + ",'"
+ dt.Rows[i - pageIndex]["SubTypeName"].ToString() +
"')\" style=\"font-size:12px;\"><dl><dt><img src=\"Images/"
+ i.ToString()
+ ".png\" width=\"30px\"></dt><dd style=\"font:normal 14px 微软雅黑, 宋体, Arial, Helvetica, sans-serif;float:left;\"><h4>"
+ dt.Rows[i - pageIndex]["SubTypeName"].ToString()
+ "</h4><p>纬度:"
+ dt.Rows[i - pageIndex]["SubType_X"].ToString()
+ "<br>经度:" + dt.Rows[i - pageIndex]["SubType_Y"].ToString()
+ "</p></dd></dl></a>");
}
}
if ((Count % 5) > 0)
{
for (int i = 0; i < (Count / 5) + 1; i++)
{
sbPage.Append("<a href=\"javascript:check(" + i + ")\" style=\"font-size:12px;\">" + (i + 1) + "</a> ");
}
}
else
{
for (int i = 0; i < (Count / 5); i++)
{
sbPage.Append("<a href=\"javascript:check(" + i + ")\" style=\"font-size:12px;\">" + (i + 1) + "</a> ");
}
}
context.Response.Write(sbList.ToString() + "<div class=\"fy\">" + sbPage.ToString() + "</div><h3 style=\"font:normal 12px/24px 微软雅黑, 宋体, Arial, Helvetica, sans-serif; text-decoration:none;\">共有 <span>" + Count + "</span> 条结果<span class=\"zkgb\"></span></h3>");
}
/// <summary>
/// 获取标注的方法:
/// </summary>
private void GetMarkerInfo()
{
string searchContent = context.Request["name"].ToString();
int pageIndex = Convert.ToInt32(context.Request["pageIndex"]);
string code = context.Request["code"].ToString();
DataTable dt = mapService.SearchAllMap(searchContent, code, out Count).Tables[0];
if (Count > 26)
{
if (dt.Rows.Count > 0)
{
List<MapModel> mapList = new List<MapModel>();
for (int i = 0; i < dt.Rows.Count; i++)
{
MapModel mapModel = new MapModel();
if (i == 0)
{
mapModel.TypeName = dt.Rows[i]["Type"].ToString();
}
mapModel.SubType_X = dt.Rows[i]["SubType_X"].ToString();
mapModel.SubType_Y = dt.Rows[i]["SubType_Y"].ToString();
mapModel.SubTypeName = dt.Rows[i]["SubTypeName"].ToString();
mapModel.Phone = dt.Rows[i]["SubType_X"].ToString();
mapModel.Address = dt.Rows[i]["SubType_Y"].ToString();
mapModel.ImageUrl = "Images/" + i.ToString() + ".png";
mapList.Add(mapModel);
}
MapList mapLists = new MapList();
mapLists.MapInfo = mapList;
mapLists.success = "OK";
string json = new JavaScriptSerializer().Serialize(mapLists);
context.Response.Write(json);
}
else
{
context.Response.Write("{success:'No'}");
}
}
else
{
if (dt.Rows.Count > 0)
{
List<MapModel> mapList = new List<MapModel>();
for (int i = 0; i < dt.Rows.Count; i++)
{
MapModel mapModel = new MapModel();
if (i == 0)
{
mapModel.TypeName = dt.Rows[i]["TypeName"].ToString();
}
mapModel.SubType_X = dt.Rows[i]["SubType_X"].ToString();
mapModel.SubType_Y = dt.Rows[i]["SubType_Y"].ToString();
mapModel.SubTypeName = dt.Rows[i]["SubTypeName"].ToString();
mapModel.Phone = dt.Rows[i]["SubType_X"].ToString();
mapModel.Address = dt.Rows[i]["SubType_Y"].ToString();
mapModel.ImageUrl = "Images/" + i.ToString() + ".png";
mapList.Add(mapModel);
}
MapList mapLists = new MapList();
mapLists.MapInfo = mapList;
mapLists.success = "OK";
string json = new JavaScriptSerializer().Serialize(mapLists);
context.Response.Write(json);
}
else
{
context.Response.Write("{success:'No'}");
}
}
}
}
public class MapList
{
private List<MapModel> _mapList;
private string _success;
public List<MapModel> MapInfo
{
get { return _mapList; }
set { _mapList = value; }
}
public string success
{
get { return _success; }
set { _success = value; }
}
}