深入学习jquery源码之高德地图组件的使用
高德地图组件是一类高度模块化的LBS服务组件,开发者通过调用相应标签便可轻松实现诸如在地图上标注点、查找附近poi、公交/驾车线路规划等功能。该类组件仅针对手机浏览器类的应用,与API相比,标签方式调用更为简单,模块化程度更高,可以极大地降低开发成本。
使用高德地图,具体请参考管网
https://lbs.amap.com/api/javascript-api/guide/abc/plugins#plugin
在页面添加 JS API 的入口脚本标签,并将其中「您申请的key值」替换为您刚刚申请的 key;
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.12&key=您申请的key值"></script>
添加div标签作为地图容器,同时为该div指定id属性;以下面的例子定义id为leakMap
<div id="leakMap" class="con" width="100%" height="100%"></div>
异步加载 JS API
同步加载
<script src="https://webapi.amap.com/maps?v=1.4.12&key=您申请的key值"></script>
<script type="text/javascript">
var map = new AMap.Map('leakMap', {
center:[117.000923,36.675807],
zoom:11
});
</script>
异步加载
<script type="text/javascript">
window.init = function(){
var map = new AMap.Map('leakMap', {
center:[117.000923,36.675807],
zoom:11
});
}
</script>
<script src="https://webapi.amap.com/maps?v=1.4.12&key=您申请的key值&callback=init"></script>
地图插件的使用
JS API 提供了众多的插件功能,这些功能不会主动随着 JSAPI 主体资源下发,需要引入之后才能使用这些插件的功能。这些功能包括:
- 服务类,如:POI搜索 PlaceSearch、输入提示 AutoComplete、路线规划 Driving/Walker/Transfer/Riding/Truck、地理编码 Geocoder、公交线路 LineSearch、公交站点 StationSearch、天气查询 Weather等;
- 地图控件,如:缩放工具条 ToolBar、比例尺 Scale、定位按钮 Geolocation等;
- 矢量图形编辑工具,如折线/多边形编辑器 PolyEditor、圆形编辑器 CircleEditor等;
- 工具类,如鼠标绘制工具 MouseTool、测距工具 RangingTool等。
异步加载插件
异步加载指的是在 JS API 加载完成之后,在需要使用到某个插件的时候,通过AMap.plugin
方法按需引入插件,在plugin
回调之后使用插件功能。
var map = new AMap.Map('container',{
zoom:12,
center:[116.39,39.9]
});
AMap.plugin('AMap.ToolBar',function(){//异步加载插件
var toolbar = new AMap.ToolBar();
map.addControl(toolbar);
});
高德地图API的封装
/** 高德autonavi 地图API Define:begin */
var AutoNaviMap = function(mapOption){
this.map = null; //高德autonavi地图对象
this.mapWrap = mapOption.mapWrap; //地图容器
this.mapRange = mapOption.mapRange; //地图范围
this.centerPoint = mapOption.centerPoint; //中心点
this.GeoServerLayers = mapOption.GeoServerLayers; //GeoServer 图层参数
this.GeoServerlayerEntities = null; //GeoServer 图层实例对象
this.zoom = mapOption.zoom==undefined ? 15 : mapOption.zoom;
this.contextMenuPositon; //右键菜单位置
this.mapLayer;//管线图层
this.heatmap;
this.toolBar = null; // 地图oolBar插件
this.markers = [];
this.infoWindow = {}; //global infoWindow
this.polygon;
this.init = function(){
var self = this;
if(!self.map){
var option = {resizeEnable : true, //监控地图容器尺寸变化,默认为false
zoom : self.zoom, //显示级别
mapStyle: "amap://styles/darkblue", //地图样式主题
features:['bg', 'point', 'building'], //地图展示元素
logo : false};
if(self.centerPoint && !$.isEmptyObject(self.centerPoint)){ //设置中心点
var transCoordinate = {
'lng':self.centerPoint.x,
'lat':self.centerPoint.y
};
if(!mapOption.noTransAmap) {
self.centerPoint.lng = self.centerPoint.x;
self.centerPoint.lat = self.centerPoint.y;
transCoordinate = self.get_GCJLngLat(self.centerPoint);
}
option['center'] = new AMap.LngLat(transCoordinate.lng, transCoordinate.lat);
}
self.map = new AMap.Map(self.mapWrap, option);
//地图单击事件
if(mapOption.click && $.isFunction(mapOption.click)) {
self.map.on('click',function(e){
var mapPoint = getMapPoint(e); //经纬度
var screenPoint = getScreenPoint(e);
mapOption.click(mapPoint, screenPoint);
}); //点事件的获取
}
//地图缩放结束事件
if(mapOption.zoomend && $.isFunction(mapOption.zoomend)) {
self.map.on('zoomend',function(e){
mapOption.zoomend();
}); //点事件的获取
}
self.map.plugin(["AMap.ToolBar"], function() {
toolBarOption = {
offset:new AMap.Pixel(10,50)
}
toolBar = new AMap.ToolBar(toolBarOption);
self.map.addControl(toolBar);
});
//添加比例尺控件
self.map.plugin(["AMap.Scale"],function(){
self.map.addControl(new AMap.Scale());
});
//地图类型切换
self.map.plugin(["AMap.MapType"],function(){
var type= new AMap.MapType({
defaultType:0 //使用2D地图
});
self.map.addControl(type);
});
$(".amap-maptype-wrap").bind('click',function(){
if(self.mapLayer && self.map){
self.mapLayer.setMap(self.map);
}
}); // 绑定地图切换插件单击事件
}
//在高德地图上 叠加 标准wms图层
setTimeout(function(){
if(self.GeoServerLayers && self.GeoServerLayers.length>0){
self.GeoServerlayerEntities = {};
for(var i=0,len=self.GeoServerLayers.length; i<len; i++){
var geoItem = self.GeoServerLayers[i];
// 创建 WMS 标准图层
var version = geoItem.GeoServerVersion || '1.1.0';
var wms = new AMap.TileLayer.WMS({
url: geoItem.GeoServerLayerUrl,
blend: true,
tileSize: 256,
visible: false,
params: {'LAYERS': geoItem.GeoServerLayerName,VERSION:version}
});
self.GeoServerlayerEntities[geoItem.GeoServerLayerCode] = wms;
//wms.show();
wms.setMap(self.map);
}
}
}, 1000);
if(mapOption.openSatelliteLayer){
var satelliteLayer = new AMap.TileLayer.Satellite();
var roadNetLayer = new AMap.TileLayer.RoadNet();
var layers = [
satelliteLayer
]
// 添加到地图上
self.map.add(layers);
}
};
/**
* checkType : 选中还是取消选中
*/
this.geoAllLayerVisibleOrHide = function(checkType){
var self = this;
var _GeoServerlayerEntities = self.GeoServerlayerEntities;
for(var o in _GeoServerlayerEntities){
if(checkType){
_GeoServerlayerEntities[o].show();
}else{
_GeoServerlayerEntities[o].hide();
}
}
}
/**
* 控制geoServer图层 显示与隐藏
* pipeCode : 管线压力级制编码
* checkType : 选中还是取消选中
*/
this.geoServerLayerVisibleOrHide = function(pipeCode, checkType){
var self = this;
var _GeoServerlayerEntities = self.GeoServerlayerEntities;
var glayer = _GeoServerlayerEntities[pipeCode];
if(checkType){
glayer.show();
}else{
glayer.hide();
}
};
this.drawPolygon = function(mPolygon){
var _self = this;
var coordinatesList = [];
if (mPolygon.points.length > 0) {
$.each(mPolygon.points, function(coordinateIndex, coordinateEntry) {
if(coordinateEntry.lng && coordinateEntry.lat && Number(coordinateEntry.lng)>0 && Number(coordinateEntry.lat)>0){
var transCoordinate = {
'lng':coordinateEntry.lng,
'lat':coordinateEntry.lat
}
//若不是从天地图转换为高德地图,则不用转换坐标系
if(!mPolygon.noTransAmap) {
var transCoordinate = _self.get_GCJLngLat(coordinateEntry);
}
coordinatesList.push(new AMap.LngLat(transCoordinate.lng, transCoordinate.lat));
}
});
if(coordinatesList.length>0) {
polygon = new AMap.Polygon({
map:_self.map,
path: coordinatesList,//设置多边形边界路径
strokeColor: mPolygon.color?mPolygon.color:"#FF33FF", //线颜色
strokeOpacity: mPolygon.opacity?mPolygon.opacity:0.2, //线透明度
strokeWeight: mPolygon.width?mPolygon.width:3, //线宽
fillColor: mPolygon.fillColor?mPolygon.fillColor:"#1791fc", //填充色
fillOpacity: mPolygon.fillOpacity?mPolygon.fillOpacity:0.35,//填充透明度
zIndex:mPolygon.zIndex
});
}
}
return polygon;
};
this.drawLine = function(mLine){
var _self = this;
var polyLine;
var coordinatesList = [];
if (mLine.pionts.length > 0) {
$.each(mLine.pionts, function(coordinateIndex, coordinateEntry) {
if(coordinateEntry.lng && coordinateEntry.lat && Number(coordinateEntry.lng)>0 && Number(coordinateEntry.lat)>0){
var transCoordinate = {
'lng':coordinateEntry.lng,
'lat':coordinateEntry.lat
}
//若不是从天地图转换为高德地图,则不用转换坐标系
if(!mLine.noTransAmap) {
var transCoordinate = _self.get_GCJLngLat(coordinateEntry);
}
coordinatesList.push(new AMap.LngLat(transCoordinate.lng, transCoordinate.lat));
}
});
if(coordinatesList.length>0) {
polyLine = new AMap.Polyline({
id : mLine.id,
map:_self.map,
path: coordinatesList, //设置线覆盖物路径
strokeColor: mLine.color, //线颜色
strokeOpacity: mLine.opacity, //线透明度
strokeWeight: mLine.width, //线宽
strokeStyle: mLine.style, //线样式
strokeDasharray: mLine.dasharray //补充线样式
});
}
if(mLine.infowindow && !$.isEmptyObject(mLine.infowindow)) {
if(!$('body').find('#infowindow').length>0) {
var html = '<div id="infowindow" style="position:absolute;display:none" class="box_wraper"><div class="box_con"><p></p></div><div class="box_img"><img src="/HRSmartGas/platform/images/box_img.png"/></div></div>';
$('body').append(html);
}
polyLine.on('mouseover',function(e) {
$('body').find('#infowindow p').html(mLine.infowindow.content);
$('#infowindow').show();
$('#infowindow').css("left",e.pixel.x-$('#infowindow').width()/2);
$('#infowindow').css("top",e.pixel.y-$('#infowindow').height());
});
polyLine.on('mouseout',function(e) {
$('#infowindow').hide();
});
}
if(mLine.onClick){
polyLine.on('click',function(e) {
mLine.onClick(e);
});
}
}
return polyLine;
};
/**
* 删除点
* point 为map地图对象, drawPoint时返回
*/
this.removePoint = function(point){
this.map.remove(point);
};
this.removeLine = function(mLine){
var _self = this;
_self.map.remove(mLine);
};
this.removePolygon = function(polygon){
var _self = this;
_self.map.remove(polygon);
};
this.drawPoint = function(mPoint){
var _self = this;
var transCoordinate = {
'lng':mPoint.lng,
'lat':mPoint.lat
};
var marker;
if(mPoint.lng && mPoint.lat && Number(mPoint.lng)>0 && Number(mPoint.lat)>0){
//若不是从天地图转换为高德地图,则不用转换坐标系
if(!mPoint.noTransAmap) {
transCoordinate = _self.get_GCJLngLat(mPoint);
}
var icon;
if(mPoint.type.imgUrl == "") {
icon = new AMap.Icon({
imageSize:new AMap.Size(mPoint.type.width,mPoint.type.height),
size: new AMap.Size(mPoint.type.width,mPoint.type.height), //图标大小
});
} else {
icon = new AMap.Icon({
imageSize:new AMap.Size(mPoint.type.width,mPoint.type.height),
size: new AMap.Size(mPoint.type.width,mPoint.type.height), //图标大小
image:mPoint.type.imgUrl
});
}
var pointOpitons = {
map:_self.map,
icon:icon,
position:[transCoordinate.lng,transCoordinate.lat],
offset:new AMap.Pixel(mPoint.type.xoffset, mPoint.type.yoffset), //偏移量
title:mPoint.type.title, //点的文字提示
extData:mPoint
};
marker = new AMap.Marker(pointOpitons);
mPoint.marker = marker;
if(mPoint.type.onClick && $.isFunction(mPoint.type.onClick)) {
marker.on('click',function(e){
mPoint.type.onClick(e.target.getExtData(),null);
}); //点事件的获取
}
if(null != mPoint.labelContent && '' != mPoint.labelContent && 'undefined' != mPoint.labelContent){
marker.setLabel({
offset: new AMap.Pixel(20, -10), //显示位置
content: mPoint.labelContent //显示内容
});
}
_self.markers.push(mPoint);
}
if(mPoint.type.showInfo && mPoint.type.infowindow && !$.isEmptyObject(mPoint.type.infowindow)) {
if(marker != undefined) {
var position = {
'lng':mPoint.lng,
'lat':mPoint.lat
};
if(!mapOption.noTransAmap) {
position = _self.get_GCJLngLat({'lng':mPoint.lng,'lat':mPoint.lat});
}
var infowindow = mPoint.type.infowindow;
var infoMouseOverWin = new AMap.InfoWindow({
isCustom:true,
content: infowindow.content,
offset: new AMap.Pixel(infowindow.xoffset,infowindow.yoffset)
});
infoMouseOverWin.open(_self.map, new AMap.LngLat(position.lng,position.lat));
_self.infoWindow.uniqueCode = mPoint.busiKey;
}
}
};
/**
* 展示自定义弹出框
*/
this.showInfoWindow = function(mPoint){
var _self = this;
if(mPoint.type.infowindow && !$.isEmptyObject(mPoint.type.infowindow)) {
var position = {
'lng':mPoint.lng,
'lat':mPoint.lat
};
if(!mapOption.noTransAmap) {
position = _self.get_GCJLngLat({'lng':mPoint.lng,'lat':mPoint.lat});
}
var infowindow = mPoint.type.infowindow;
var infoMouseOverWin = new AMap.InfoWindow({
isCustom:true,
content: infowindow.content,
offset: new AMap.Pixel(infowindow.xoffset,infowindow.yoffset)
});
infoMouseOverWin.open(_self.map, new AMap.LngLat(position.lng,position.lat));
_self.infoWindow.uniqueCode = mPoint.busiKey;
}
}
this.getInfoWindowUnique = function(){
var _self = this;
return _self.infoWindow.uniqueCode;
}
this.clearGraphics = function(type) {
var _self = this;
for(var i =0; i<_self.markers.length; i++){
if(type){
if((_self.markers[i].node == type))
_self.map.remove(_self.markers[i].marker);
}else{
_self.map.remove(_self.markers[i].marker);
}
}
};
/**
* e 鼠标事件对象
*/
function getScreenPoint(e){
return new SreenPoint({x:e.pixel.x, y:e.pixel.y});
};
/**
* e 鼠标事件对象
*/
function getMapPoint(e){
return new MapPoint({'lng' : e.lnglat.lng, 'lat' : e.lnglat.lat});
};
//绘制管线图层
this.drawArcgisTile = function(url,token,callback) {
var _self = this;
if(_self.mapLayer){
mapLayer.setTileUrl(callback);
} else {
_self.mapLayer = new AMap.TileLayer({
zIndex:20,
getTileUrl: function(x,y,z){
return url+'/'+ z +'/'+ y +'/'+ x+'?token='+token;
}
});
_self.mapLayer.setMap(_self.map);
}
return _self.mapLayer;
};
//重新加载arcgis管线图层
this.reloadArcgisTile = function(){
if(_self.mapLayer && _self.map){
_self.mapLayer.setMap(_self.map);
}
}
//画热力图
this.drawHeatMap = function(heatMap) {
var _self = this;
var coordinatesList = [];
if (heatMap.data.length > 0) {
$.each(heatMap.data, function(coordinateIndex, coordinateEntry) {
if(coordinateEntry.lng && coordinateEntry.lat && Number(coordinateEntry.lng)>0 && Number(coordinateEntry.lat)>0){
var transCoordinate = {
'lng':coordinateEntry.lng,
'lat':coordinateEntry.lat
}
//若不是从天地图转换为高德地图,则不用转换坐标系
if(!heatMap.noTransAmap) {
transCoordinate = _self.get_GCJLngLat(coordinateEntry);
}
coordinatesList.push(new AMap.LngLat(transCoordinate.lng, transCoordinate.lat));
}
});
}
if(coordinatesList.length>0) {
_self.map.plugin(["AMap.Heatmap"], function() {
//初始化heatmap对象
_self.heatmap = new AMap.Heatmap(_self.map, {
radius: 80, //给定半径
opacity: [0, 0.8]
});
//设置数据集
_self.heatmap.setDataSet({
data: coordinatesList,
max: 2
});
});
}
}
/**
*画圆 获取中心点及半径
*20180122
*/
this.draw =function (){
var _self = this;
var mouseTool = new AMap.MouseTool(_self.map);
//自定义图形样式
mouseTool.polyline({
strokeColor:"#f50", // 线条颜色,十六进制
strokeOpacity:0.5, // 线条透明度
strokeWeight:10, // 线条宽度
strokeStyle:"dashed" // 线条样式 solid || dashed
});
//在地图中添加MouseTool插件
mouseTool.circle(); //用鼠标工具画圆
AMap.event.addListener( mouseTool,'draw',function(e){ //添加事件
console.log(e.obj.getRadius());//获取半径
console.log(e.obj.getCenter());//获取中心点
showChoseDevice(e.obj.getRadius(),e.obj.getCenter());
mouseTool.close(true);//关闭当前鼠标操作
});
} ;
//画圆
this.drawCircle = function(circle){
var _self = this;
var center = new AMap.LngLat(circle.center.lng,circle.center.lat);
var circleOptions = {
center:center,
zIndex:1000,
radius:circle.radius, //半径1公里
strokeColor: "#F33", //线颜色
strokeOpacity: 1, //线透明度
strokeWeight: 3, //线粗细度
fillColor: "#ee2200", //填充颜色
fillOpacity: 0.35//填充透明度
};
var _circle = new AMap.Circle(circleOptions);
_circle.setMap(_self.map);
circle.marker = _circle;
}
this.circleContains = function(circle,point) {
var _self = this;
var transCoordinate = {
'lng':point.lng,
'lat':point.lat
}
//若不是从天地图转换为高德地图,则不用转换坐标系
if(!point.noTransAmap) {
transCoordinate = _self.get_GCJLngLat(point);
}
var _point = new AMap.LngLat(transCoordinate.lng,transCoordinate.lat);
var isContains = circle.marker.contains(_point);
return isContains;
}
//绑定地图缩放事件
this.bindZoomChange = function(callBack) {
var _self = this;
_self.map.on('zoomchange', function(e) {
callBack(_self.map.getZoom());
});
}
//绑定地图单击事件
this.bindClick = function(callBack) {
var _self = this;
_self.map.on('click', function(e) {
callBack(e.lnglat.getLng(),e.lnglat.getLat(),_self.map.getZoom());
});
}
/**
* 获取缩放等级
*/
this.getZoom = function(){
var _self = this;
return _self.map.getZoom();
}
//显示或隐藏热力图
this.showHeatMap = function(isShow) {
var _self = this;
if(_self.heatmap) {
if(isShow) {
_self.heatmap.show();
} else {
_self.heatmap.hide();
}
}
}
//添加右键菜单获取坐标
this.addGetLnglatMenu = function() {
var _self = this;
var menu = new AMap.ContextMenu();
//添加菜单项
menu.addItem("发送任务",function() {
debugger;
mapDbClick(contextMenuPositon.getLat(),contextMenuPositon.getLng());
//alert(contextMenuPositon.getLng() + "," + contextMenuPositon.getLat());
},0);
//为地图注册rightclick事件获取鼠标点击出的经纬度坐标
var clickEventListener = _self.map.on('rightclick', function(e) {
menu.open(_self.map,e.lnglat);
contextMenuPositon = e.lnglat;
});
};
this.setCenter = function(lnt,lat) {
var transCoordinate = {
'lng':lnt,
'lat':lat
};
var _self = this;
if(!mapOption.noTransAmap) {
_self.centerPoint.lng = lnt;
_self.centerPoint.lat = lat;
transCoordinate = _self.get_GCJLngLat(_self.centerPoint);
}
_self.map.setCenter(new AMap.LngLat(transCoordinate.lng, transCoordinate.lat));
};
this.closeInfoWindow = function(infoWindow) {
var _self = this;
_self.map.clearInfoWindow();
};
this.fromLngLatToContainerPixel = function(mPoint) {
var _self = this;
var retObj = _self.map.lnglatToPixel(new AMap.LngLat(mPoint.lng,mPoint.lat));
return new SreenPoint(retObj);
};
this.fromContainerPixelToLngLat = function(mPoint) {
var _self = this;
var retObj = _self.map.pixelToLngLat(new AMap.Pixel(mPoint.x,mPoint.y));
return new MapPoint(retObj);
};
this.setFitView = function() {
var _self = this;
_self.map.setFitView();
};
this.zoomOut = function() {
var _self = this;
_self.map.zoomOut();
}
this.get_GCJLngLat = function(mPoint) {
var retObj = {};
var CT = new CoordinateTransform(mPoint.lat, mPoint.lng, CoordinateSys.WGS84);//CoordinateSys.WGS84 是转换前的坐标系
var retValue = new Object();
if (CT.WGS84ToGCJ02()== false)//WGS84ToBD09()方法 WGS84转BD坐标,如果是转成火星坐标改调用WGS84ToGCJ02()
console.info(CT.get_ErrMsg());
retObj.lat = CT.get_GCJLat() == 0 ? mPoint.lat : CT.get_GCJLat();//获取转换后的高德坐标纬度
retObj.lng = CT.get_GCJLng() == 0 ? mPoint.lng : CT.get_GCJLng();//获取转换后的高德坐标精度
return retObj;
};
};
function openWindowTask(tltle,url){
var options = {
modal : true,
title : tltle,
collapsible : false,
minimizable : false,
maximizable : false,
closable : true,
closed : false
};
var uid = "self_card_";
options["id"] = uid;
winFormDesigner = UIFactory.getUI(uid);
if(!winFormDesigner){
winFormDesigner = UIFactory.create(xpad.ui.Window, options);
}
var root = jQuery("body");
var offset = root.offset();
var winleft = 0;
var wintop = 0;
var newSize = {};
newSize["left"] = (jQuery("body").width()-450)/2;
newSize["top"] = 20;
newSize["width"] = 450;//jQuery("body").width();
newSize["height"] = 500;//jQuery("body").height();
winFormDesigner.window("resize", newSize);
setTimeout(function(){
winFormDesigner.loadURL(url);
}, 0);
}
AutoNaviMap.CLASS_NAME = "AutoNaviMap";
/**高德autonavi 地图API Define:end */
业务API的封装
/** ServiceMap Define:begin */
var ServiceMap = function(mapOption){
this.map = new mapOption.mapClass(mapOption); //地图对象
this.map.init(); //初始化地图组件
/**
* 画线
*/
this.drawLine = function(line){
return this.map.drawLine(line);
};
/**
* 画点
*/
this.drawPoint = function(point){
return this.map.drawPoint(point);
};
/**
* 地图经纬度坐标转换为平面地图像素坐标
*/
this.fromLngLatToContainerPixel = function(point) {
return this.map.fromLngLatToContainerPixel(point);
};
/**
* 平面地图像素坐标转换为地图经纬度坐标
*/
this.fromContainerPixelToLngLat = function(point) {
return this.map.fromContainerPixelToLngLat(point);
};
/**
* 控制geoServer图层 显示与隐藏
* pipeCode : 管线压力级制编码
* checkType : 选中还是取消选中
*/
this.geoServerLayerVisibleOrHide = function(pipeCode, checkType){
return this.map.geoServerLayerVisibleOrHide(pipeCode, checkType);
}
/**
* checkType : 选中还是取消选中
*/
this.geoAllLayerVisibleOrHide = function(checkType){
return this.map.geoAllLayerVisibleOrHide(checkType);
}
/**
* 根据覆盖物设置合适的视野
*/
this.setFitView = function() {
this.map.setFitView();
};
/**
* 删除点
* point 为map地图对象, drawPoint时返回
*/
this.removePoint = function(point){
this.map.removePoint(point);
}
this.clearGraphics = function(mpoint){
return this.map.clearGraphics(mpoint);
}
/**
* 删除线
* line 为map地图对象, drawLine时返回
*/
this.removeLine = function(line){
this.map.removeLine(line);
}
this.removePolygon = function(polygon){
this.map.removePolygon(polygon);
}
/**
* 设置中心点
* lng 纬度
* lat 经度
*/
this.centerAt = function(lng, lat){
this.map.centerAt(lng, lat);
}
this.setCenter = function(lng, lat){
this.map.setCenter(lng, lat);
}
/**
* 设置级别
* zoom Number
*/
this.setZoom = function(zoom){
this.map.setZoom(zoom);
}
/**
* 地图可视区域
* 返回对象: MapBounds
*/
this.getBounds = function(){
return this.map.getBounds();
}
/**
* 圈选要素
* layer : 子图层索引
* strWhere : 查询条件
* callBack : 回调函数, 返回feature列表
*/
this.selectFeature = function(layer, strWhere, callBack){
this.map.selectFeature(layer, strWhere,callBack);
}
/**
* 获取圈选覆盖物
*/
this.selectOverlay = function(callBack){
this.map.selectOverlay(callBack);
}
/**
* 获取缩放等级
*/
this.getZoom = function(){
return this.map.getZoom();
}
/**
* 关闭弹出信息框
* @returns
*/
this.closeInfoWindow = function(){
this.map.closeInfoWindow();
}
/**
* 展示自定义弹出框弹出框
*/
this.showInfoWindow = function(mPoint){
this.map.showInfoWindow(mPoint);
}
/**
* 获取弹出框唯一id,通常用业务唯一标识表示
*/
this.getInfoWindowUnique = function(){
return this.map.getInfoWindowUnique();
}
this.drawPolygon = function(mPolygon){
return this.map.drawPolygon(mPolygon);
}
};
ServiceMap.CLASS_NAME = "ServiceMap";
/** ServiceMap Define:end */
使用地图组件进行画点画线等操作
html
<div id="leakMap" class="con" width="100%" height="100%"></div>
js
$(function(){
var mapOption = {
'mapWrap' : 'leakMap', //地图容器
/*'mapRange' : {'xmin':70.45193,'ymin':15.14801,
'xmax':137.424587,'ymax':53.976474}, //坐标范围
*/ 'centerPoint' : {'x':116.383105, 'y':39.974672}, //中心点
'mapClass' : AutoNaviMap, //地图组件
'isAddNavigationControl':true, //工具条
'isAddControl':false, //类别切换
'zoom': 10,
'GeoServerUrl': 'http://6666/geoserver',
'GeoServerLayers': getGeoServerParameters(),
'zoomend': function(mapPoint, screenPoint){
controlLayers(serviceMap.getZoom());
},
'click' : function(mapPoint, screenPoint){ //地图点击事件
console.log('地图坐标:(' + mapPoint.lng + ', ' + mapPoint.lat +');屏幕坐标:(' + screenPoint.x + ',' + screenPoint.y + ')');
},
openSatelliteLayer:false
};
serviceMap = new ServiceMap(mapOption);
})
//所有已绘制的线和点
var lines = [],drawPoints = [],drawNewPoints =[];
var Leak = {
/**
* 画线
*/
drawLine:function(points){
if(!$.isEmptyArray(lines)){
serviceMap.removeLine(lines[0]);
}
//画线
var line = {
'color' : '#FF0033',
'width' : 3,
pionts:points,
};
lineObj = serviceMap.drawLine(line);
lines.push(lineObj);
},
removeLine:function(){
serviceMap.removeLine(lines);
},
/**
* 画点
*/
drawPoint:function(point){
drawPoints.push(point);
serviceMap.drawPoint(point);
},
drawNewPoint:function(point){
drawNewPoints.push(point);
serviceMap.drawPoint(point);
},
/**
* 删除点
*/
removePoint:function(){
if(!$.isEmptyArray(drawPoints)){
for(var i=0;i<drawPoints.length;i++){
serviceMap.removePoint(drawPoints[i].marker );
}
drawPoints.length = 0;
}
},
removeNewPoint:function(){
if(!$.isEmptyArray(drawNewPoints)){
for(var i=0;i<drawNewPoints.length;i++){
serviceMap.removePoint(drawNewPoints[i].marker );
}
drawNewPoints.length = 0;
}
},
showInfoWindow:function(point){
serviceMap.showInfoWindow(point);
},
closeInfoWindow:function(){
serviceMap.closeInfoWindow();
},
centerAt:function(lng, lat){
serviceMap.setCenter(lng, lat);
}
}
以上就完成了高德地图组件的封装
使用封装的地图组件实现画点画线等基础操作
layui前端插件,实现选中一条列表数据进行画点画线弹出框等操作
hookMethod:function(obj){
var data = obj.data;
if("scanLeak"==obj.event){
var points = [];
Leak.removePoint(); // removePoint.call(Leak)
Leak.removeLine();
Leak.closeInfoWindow();
var url = CONTEXT_PATH + '/cusviews/leak/listLeakPoint';
var param = {
checkId : data.checkId
}
var retData = $.getData(url,param);
if(1000 != retData.status){
layer.msg('获取数据失败', {icon: 5});
return;
}
if(0==retData.data.length){
layer.alert('无地图坐标', {
skin: 'layui-layer-lan'
,closeBtn: 0
});
return;
}
var data = retData.data;
if(!$.isEmptyArray(data)){
for(var i=0;i<data.length;i++){
if($.isEmptyStr(data[i].lng) || $.isEmptyStr(data[i].lat)){
continue;
}
var point = {
"lng":data[i].lng,
"lat":data[i].lat,
};
points.push(point);
Leak.centerAt(data[i].lng,data[i].lat);
var drawPoint = {
"lng":data[i].lng,
"lat":data[i].lat,
"type":pointType[1]
}
if(0 == i){
drawPoint.type = pointType[3]
}
else if((data.length - 1) == i){
drawPoint.type = pointType[4]
}
var info = [];
var checkDate = data[i].checkDate==null?"":data[i].checkDate;
var startTime = data[i].startTime==null?"":data[i].startTime;
var endTime = data[i].endTime==null?"":data[i].endTime;
var userArea = data[i].userArea==null?"":data[i].userArea;
var checkUser = data[i].checkUser==null?"":data[i].checkUser;
info.push("<div class='info' style='width: 300px; height: 140px;'>");
info.push("<div class='info-top'>");
/*info.push("<div>"+userArea+"</div>");*/
info.push("<a class='iconfont' onclick='Leak.closeInfoWindow()'></a></div>");
info.push("<div class=;info-middle'>");
info.push("<div class='tCon' id='stationDiv'>");
info.push("<div class='tList'>");
info.push("<p class='input-item'>检测日期:"+checkDate+"</p>");
info.push("<p class='input-item'>开始时间:"+startTime+"</p>");
info.push("<p class='input-item'>结束时间:"+ endTime +"</p>");
info.push("<p class='input-item'>用户片区:"+ userArea +"</p>");
info.push("<p class='input-item'>检测人 :"+checkUser +"</p></div></div></div>");
drawPoint.type["infowindow"] ={
content: info.join(""),
xoffset: 0,
yoffset:-31,
width:360,
height:100
};
drawPoint.type["onClick"] = function(point, e){
Leak.showInfoWindow(point) // showInfoWindow.call(Leak,point)
}
if(0 == i||(data.length - 1) == i){
Leak.drawPoint(drawPoint);
}
}
Leak.drawLine(points);
}else{
layer.alert('无地图坐标', {
skin: 'layui-layer-lan'
,closeBtn: 0
});
return;
}
}else if("scanLeakPoint"==obj.event){
var points = [];
Leak.removeNewPoint();
Leak.closeInfoWindow();
var url = CONTEXT_PATH + '/cusviews/leak/listSlPoint';
var param = {
checkId : data.checkId
}
var retData = $.getData(url,param);
if(1000 != retData.status){
layer.msg('获取数据失败', {icon: 5});
return;
}
if(0==retData.data.length){
layer.alert('无地图坐标', {
skin: 'layui-layer-lan'
,closeBtn: 0
});
return;
}
var data = retData.data;
if(!$.isEmptyArray(data)){
for(var i=0;i<data.length;i++){
if($.isEmptyStr(data[i].lng) || $.isEmptyStr(data[i].lat)){
continue;
}
var point = {
"lng":data[i].lng,
"lat":data[i].lat,
};
points.push(point);
Leak.centerAt(data[i].lng,data[i].lat);
$.each(data[i],function(n,m){
var pointColor = {};
pointColor= {
"imgUrl":CONTEXT_PATH+"/view/cusviews/images/red_point.png",
"height":36,
"width":36,
"xoffset": -10,
"yoffset": -34,
'onClick' : function(point, e){
console.log('坐标:LAT:' + point.lat + ';LNG:' + point.lng);
},
}
var drawPoint = {};
drawPoint = {
"lng":data[i].lng,
"lat":data[i].lat,
"type":pointType[1]
}
drawPoint.type = pointColor
var info = [];
var checkDate = data[i].checkDate==null?"":data[i].checkDate;
var normalValue = data[i].normalValue==null?"":data[i].normalValue;
info.push("<div class='info' style='width: 300px; height: 58px;'>");
info.push("<div class='info-top'>");
/*info.push("<div>"+checkDate+"</div>");*/
info.push("<a class='iconfont' onclick='Leak.closeInfoWindow()'></a></div>");
info.push("<div class=;info-middle'>");
info.push("<div class='tCon' id='stationDiv'>");
info.push("<div class='tList'>");
info.push("<p class='input-item'>检测时间:"+ checkDate +"</p>");
info.push("<p class='input-item'>检测浓度 :"+normalValue +"</p></div></div></div>");
var myInfo = {newInfo:{
content: info.join(""),
xoffset: 0,
yoffset:-31,
width:360,
height:100
}}
for(var j in myInfo){
var mythisInfo = {};
mythisInfo = myInfo[j];
drawPoint.type["infowindow"] =mythisInfo;
window.drawPoints.push(drawPoint);
}
Leak.drawNewPoint(drawPoint);
drawPoint.type["onClick"] = function(point, e){
Leak.showInfoWindow(point)
}
})
}
}else{
layer.alert('无地图坐标', {
skin: 'layui-layer-lan'
,closeBtn: 0
});
return;
}
}
}
一些应用
首页点击跳转地图页面
function(){
ProdataShow.initOther();
});
/**
* 首页
*/
var ProdataShow = {
initOther:function(){
setTimeout(function(){
$(".amap-maptypecontrol").css("top","38px");
$(".amap-toolbar").css("top","86px");
}, 3000);
},
indexSkip:function(type){
if($.isEmptyStr(type)){
layer.alert('地址不存在!', {icon: 0});
return;
}
var url = ""
switch(type)
{
case 'rushRepair':
url = CONTEXT_PATH + "/cusviews/rush/index";
break;
case 'leakCheck':
url = CONTEXT_PATH + "/cusviews/leak/index";
break;
default:
url = CONTEXT_PATH + "/cusviews/index";
}
window.location.href = url;
}
}
<span onclick="ProdataShow.indexSkip('leakCheck')">
第一次加载地图弹出框用freemarker的渲染数据
layui.use(plugins, function(){
var option = $.extend({elem: "#" + _self.container,
url : _self.url,
cols: _self.title,
method: RequestMethod.METHOD_POST,
id : _self.tableId,
even: true,
page: true, //是否显示分页
pageNum: 1,
limit: _self.pageSize, //每页默认显示的数量
limits:[5,10,15,20,30],
done:function(res, curr, count){
if(_self.afterDone && $.isFunction(_self.afterDone)){
_self.afterDone(res, curr, count);
}
}}, _self.layOption);
//展示已知数据
layui.table.render(option);
//渲染部分layui组件
_self.initLayuiPlugin();
//监听工具条
layui.table.on('tool(' + _self.container + ')', function(obj){ //注:tool是工具条事件名,test是table原始容器的属性 lay-filter="对应的值"
if(_self.hookMethod && $.isFunction(_self.hookMethod)){
_self.hookMethod(obj); //回调 子类中的 钩子方法
}
});
//复选框事件选中以后回调
layui.table.on('checkbox(' + _self.container + ')', function(obj){
if(_self.tableAfterChecked && $.isFunction(_self.tableAfterChecked)){
_self.tableAfterChecked(obj); //回调 子类中的 钩子方法
}
});
});
实现页面加载自动画点与初始化弹出框信息
afterDone:function(res, curr, count){
Device.removeDevicePoints(stationPoints);
Device.removeDevicePoints(boxPoints);
Station.drawPoint(res.data);
}
var Station = {
/**
* 画调压站/箱的点
*/
drawPoint:function(data){
if($.isEmptyArray(data)){
return;
}
for(var i=0;i<data.length;i++){
var point = {
'lng':data[i].lng,
'lat':data[i].lat,
'type': pointType[0],
'labelContent':data[i].deviceName,
'data':data[i]
}
var entity = data[i];
entity['title'] = data[i].deviceName
if(1 == $("#stationType").val()){
Device.drawPoint(entity,point,'station');
}else{
Device.drawPoint(entity,point,'box');
}
}
}
}
var stationPoints = [],boxPoints=[]
var Device = {
drawPoint:function(entity,point,type){
switch(type)
{
case 'station':
var style = {
width:"300px",
height:"455px"
}
point['type']={
imgUrl: CONTEXT_PATH+"/view/cusviews/images/normal_station.png", //"../assetdigit/images/br_logo.png",
width: 36,
height: 36,
xoffset: 0,
yoffset: 0,
title: entity['title'],
showInfo: false,
infowindow:{
content: getPopContentTpl(entity,'station',style), //getPopContentTpl(entity, funCode, facilityType),
xoffset: 32,
yoffset:-25,
width: 500,
height: 145
},
"onClick": function(mdata){
serviceMap.showInfoWindow(mdata);
setTimeout("Device.showDeviceLineChart('"+entity.deviceCode+"')","1000");
$(".tCon").scrollBar();
}
}
stationPoints.push(point);
break;
case 'box':
var style = {
width:"300px",
height:"455px"
}
point['type']={
imgUrl: CONTEXT_PATH+"/view/cusviews/images/normal_box.png",
width: 36,
height: 36,
xoffset: 0,
yoffset: 0,
title: entity['title'],
showInfo: false,
infowindow:{
content: getPopContentTpl(entity,'station',style),
xoffset: 32,
yoffset:-25,
width: 500,
height: 145
},
"onClick": function(mdata){
serviceMap.showInfoWindow(mdata);
setTimeout("Device.showDeviceLineChart('"+entity.deviceCode+"')","1000");
$(".tCon").scrollBar();
}
}
boxPoints.push(point);
break;
default:
break;
}
serviceMap.drawPoint(point);
$(".tCon").scrollBar();
},
removeDevicePoints:function(points){
if($.isEmptyArray(points)){
return;
}
for(var i=0;i<points.length;i++){
try{
serviceMap.removePoint(points[i].marker);
}catch(err){
continue;
}
}
//清空数组
points.splice(0,points.length);
}
}
freemarker第一次数据渲染,再点击加载数据
var tplConfig = {
station:{
popWindowSize:{
width: 320,
height: 145
},
infoTpl:'<div class="tCon" id="stationDiv"><div class="tList">'+
'<p>设备编码:${deviceCode}</p>'+
'<p>设备名称:${deviceName}</p>'+
'<p>启用日期:${startDate}</p>'+
'<p>设备规格:${deviceSpec}</p>'+
'<p>设备型号:${deviceModel}</p>'+
'<p>运行状态:${runState}</p>'+
'<p>管理单位:${deviceMgt}</p>'+
'<p>温度(℃):${weath}</p>'+
'<p>有无监控:${hasAlarm}</p></div><div class="tChart" id="pressLine">折线图</div></div>'+
'<div class="tNav">'+
'<a href="javascript:void(0)" onclick="Device.getStationDetail(0,${deviceId})">基础信息</a>'+
'<a href="javascript:void(0)" onclick="Device.getStationDetail(1,'${deviceCode}')">诊断记录</a>'+
'<a href="javascript:void(0)" onclick="Device.getStationDetail(2,${deviceId})">运行记录</a>'+
'<a href="javascript:void(0)" onclick="Device.getStationDetail(3,${deviceId})">维检修记录</a></div>'
}
}
function getPopContentTpl(entity,funCode,style){
var contentHtml = tplConfig[funCode]["infoTpl"];
var content = fillTplWithEntity(entity,contentHtml);
return createInfoWindow(entity.title,content,style);
}
function fillTplWithEntity(entity, tpl){
var regex = /\$\{(.+?)\}/g; // {} 花括号,大括号
var $fields = tpl.match(regex);
for(var i=0,len=$fields.length; i<len; i++){
var $field = $fields[i],
field = $field.substr(2, $field.length-3);
if($.isEmptyStr(entity[field])){
tpl = tpl.replace($field, '');
}else{
tpl = tpl.replace($field, entity[field]);
}
}
return tpl;
}
function createInfoWindow(title, content, _style) {
var info = document.createElement("div");
info.className = "info";
//可以通过下面的方式修改自定义窗体的宽高
info.style.width = _style.width||"400px";
info.style.height = _style.height||"420px";
// 定义顶部标题
var top = document.createElement("div");
var titleD = document.createElement("div");
var closeX = document.createElement("a");
closeX.className = "iconfont";
top.className = "info-top";
titleD.innerHTML = title;
//closeX.src = "https://webapi.amap.com/images/close2.gif";
closeX.onclick = closeInfoWindow;
top.appendChild(titleD);
top.appendChild(closeX);
info.appendChild(top);
// 定义中部内容
var middle = document.createElement("div");
middle.className = "info-middle";
middle.style.backgroundColor = '';
middle.innerHTML = content;
info.appendChild(middle);
// 定义底部内容
var bottom = document.createElement("div");
bottom.className = "info-bottom";
bottom.style.position = 'absolute';
bottom.style.top = info.style.height || '0px';
bottom.style.margin = '0 auto';
var sharp = document.createElement("p");
sharp.className = "angle";
//sharp.src = "https://webapi.amap.com/images/sharp.png";
bottom.appendChild(sharp);
info.appendChild(bottom);
return info;
}
/**
* 关闭弹出信息框
* @returns
*/
function closeInfoWindow(){
serviceMap.setCenter(116.383105,39.974672);
serviceMap.closeInfoWindow();
}
点击重新渲染数据
getStationDetail:function(type,deviceCode){
var url = ""
switch(type)
{
case 0:
url = CONTEXT_PATH + "/cusviews/dev/getStationById"
break;
case 1:
url = CONTEXT_PATH +"/cusviews/dev/getLastTimeDiagRecord"
break;
case 2:
url = CONTEXT_PATH+"/cusviews/dev/getLastTimeRunRecord"
break;
case 3:
url = CONTEXT_PATH + "/cusviews/dev/getLastTimeRepairRecord"
break;
}
var param;
if(1==type){
param = {
deviceCode:deviceCode
}
}else{
param = {
deviceId:deviceCode
}
}
$("#stationDiv").load(url,param)
}
@RequestMapping("/getStationById")
public String getStationById(String deviceId,ModelMap model)
{
PrPreStation record = stationService.getStationById(deviceId);
model.addAttribute("record", record);
return "cusviews/v_devices/station/stationMainInfo";
}
stationMainInfo.html
<div class="tList">
<#if record??>
<p>设备编码:${record.deviceCode!''}</p>
<p>设备名称:${record.deviceName!''}</p>
<p>启用日期:${record.startDate}</p>
<p>设备规格:${record.deviceSpec!''}</p>
<p>设备型号:${record.deviceModel!''}</p>
<p>运行状态:${record.runState!''}</p>
<p>管理单位:${record.deviceMgt!''}</p>
</div>
<div class="tList">
<p>温度(℃):${record.weath!''}</p>
<p>有无监控:${record.hasAlarm!''}</p>
</div>
</#if>
<div class="tChart" id="pressLine">折线图</div>
<script>
$(function(){
Device.showDeviceLineChart('${record.deviceCode!''}');
})
</script>
同一张表,根据不同的类型加载不同的地图数据
<label><i class="iconfont"></i><span onclick="Device.clickDeviceType('station')">站</span><input type="checkbox" /></label>
<label><i class="iconfont"></i><span onclick="Device.clickDeviceType('box')">箱</span><input type="checkbox" /></label>
<div class="bb_box" id="deviceListDiv" style="display:none">
</div>
var Device = {
clickDeviceType:function(type){
if($.isEmptyStr(type)){
return;
}
var url = "";
switch(type)
{
case 'station':
url = CONTEXT_PATH + "/cusviews/dev/showStationList/1";
Device.removeDevicePoints(boxPoints);
Device.removeDevicePoints(wellPoints);
Device.removeDevicePoints(pilePoints);
break;
case 'box':
url = CONTEXT_PATH + "/cusviews/dev/showStationList/2";
Device.removeDevicePoints(stationPoints);
Device.removeDevicePoints(wellPoints);
Device.removeDevicePoints(pilePoints);
break;
default:
break;
}
$("#deviceListDiv").css("display","block");
$("#deviceListDiv").load(url)
}
@RequestMapping("/showStationList/{type}")
public String showStationList(@PathVariable("type")String type,ModelMap model)
{
model.addAttribute("stationType", type);
return "cusviews/v_devices/stationList";
}
stationList.html
<form id="stationList-QueryForm">
<div class="side_search">
<input type="text" name="hasAlarm" placeholder="请输入搜索内容" />
<a id="search" action="listQuery(this,event)">搜索</a>
</div>
</form>
<div class="lay_list">
<table id="stationList" lay-filter="stationList">
</table>
</div>
<div>
<input type="hidden" value="${stationType!''}" id="stationType">
</div>
<script src="${rc.contextPath}/view/cusviews/v_devices/js/List.js"></script>
List.js
this.layOption = {
where:{
preBoxType:$("#stationType").val()
}
};
其他实现高德地图API封装的方法
加载方法实现初始化操作
var AutoNaviMap = function(mapOption){
this.init = function(){
};
this.drawLine = function(mLine){
}
this.drawPoint = function(mPoint){
}
this.centerAt = function(lng, lat){
this.map.setCenter(new AMap.LngLat(lng, lat));
};
this.setZoom = function(zoom){
this.map.setZoom(zoom);
};
}
AutoNaviMap.CLASS_NAME = "AutoNaviMap";
自己封装对象,实现地图API
var Map = function(mapOption){
this.map = new mapOption.mapClass(mapOption); //地图对象
this.map.init(); //初始化地图组件
/**
* 画线
*/
this.drawLine = function(line){
return this.map.drawLine(line);
};
/**
* 画点
*/
this.drawPoint = function(point){
return this.map.drawPoint(point);
};
/**
* 设置中心点
* lng 经度
* lat 纬度
*/
this.centerAt = function(lat, lng){
this.map.centerAt(lat, lng);
}
/**
* 设置级别
* zoom Number
*/
this.setZoom = function(zoom){
this.map.setZoom(zoom);
}
};
Map.CLASS_NAME = "Map";
定义全局初始化方法
var tiledMapServiceURL="";
var pipelineMapServiceURL = "http://1246:8080/MapServer";
var geometryServiceURL = "";
var companylat;
function mapLoad(){
if (companylat && companylat != "null" && companylat != "" && companylat != '""') {
} else {
companylng = 532000;
companylat = 358000;
}
var mapOption = {
'mapWrap' : 'map_con', //地图容器
'dynamicMapServiceUrl' : pipelineMapServiceURL,
'tiledMapServiceUrl' : tiledMapServiceURL,
'mapRange' : {
'xmin' : 409439.40635501774,
'ymin' : 328530.8110858157,
'xmax' : 630292.6726449793,
'ymax' : 394303.4774500003
},
'centerPoint' : {
'x' :companylng ,
'y' :companylat
}, //中心点
'mapClass' : AutoNaviMap, //地图组件
//地图点击事件
'click' : function(mapPoint, screenPoint){
//console.log('地图坐标:(' + mapPoint.lng + ', ' + mapPoint.lat +');屏幕坐标:(' + screenPoint.x + ',' + screenPoint.y + ')');
},
'wkid':4326
};
map = new Map(mapOption);
}
function loadMap() {
var mapOption = {
'mapClass' : ArcgisMap,
'mapWrap' : 'map_con',
'dynamicMapServiceUrl' : pipelineMapServiceURL,
'tiledMapServiceUrl' : tiledMapServiceURL,
'mapRange' : {
'xmin' : 409439.40635501774,
'ymin' : 328530.8110858157,
'xmax' : 630292.6726449793,
'ymax' : 394303.4774500003
},
'centerPoint' : {
'x' : 532000,
'y' : 358000
},
'wkid' : 21420
};
map = new Map(mapOption);
}
}
通过调用全局的初始化方法来初始化自己封装的全局Map对象,通过Map对象来调用高德地图API,实现业务方法
var root = null;
var Map;
var initZoom = 14;
window.onload=function(){
root = $("#root").val();
init();
}
function init(){
mapLoad();
Map.map.map.onZoomStart = function() {
}
Map.map.map.onUpdateStart = function() {
}
Map.centerAt('116.397477', '39.908692');
Map.setZoom(initZoom);
}
function drowLine(pionts, color){
var mLine = {
'pionts' : pionts,
'color' : color,
'width' : 3,
'onClick' : function(line, e) {
if($.isFunction(onclick)){
onclick(line, e);
}
}
};
return Map.drawLine(mLine);
}
function markPoint(x, y, markData, flag){
Map.markPoint(x, y);
}
function getAll(){
$.ajax({
type : "POST",
url : root + "/getAllInfo",
data : {},
success : function(illegalPlaceData){
for(var i=0; i < illegalPlaceData.GL_ILLEGAL_PLACE.length; i++){
x = Data.PLACE[i].data.PLACE_X;
y = Data.PLACE[i].data.PLACE_Y;
illegalPlacePoints.push(drowPoint(x, y, 'wzzy.png', PLACE[i], 'ZY', function(point,e){
var screenPoint = {x:e.clientX, y:e.clientY};
var content = infoWindowStrategy(point);
var infoWindow = {content:content.html, lng:e.lnglat.lng, lat:e.lnglat.lat};
Map.showInfoWindow(infoWindow);
}));
}
}
});
}
function getExceptionInfo(){
$.ajax({
type : "POST",
url : root + "/getExceptionInfo",
data : {},
success : function(exceptionData){
for(var i=0; i < exceptionData.POINT.length; i++){
x = exceptionData.POINT[i].data.LEAKPOINT_X;
y = exceptionData.POINT[i].data.LEAKPOINT_Y;
exceptionPoints.push(drowPoint(x, y, 'psd.png', exceptionData.GL_LEAKPOINT[i], 'PSD', function(point,e){
var screenPoint = {x:e.clientX, y:e.clientY};
var content = infoWindowStrategy(point);
var infoWindow = {content:content.html, lng:e.lnglat.lng, lat:e.lnglat.lat};
Map.showInfoWindow(infoWindow);
}));
}
}
});
}
function drowPoint(zbx, zby, img, pdata, flag, onclick) {
var point = {
'lng' : zbx,
'lat' : zby,
"flag":flag,
"data":pdata,
"onclick":onclick,
'type' : {
'imgUrl' : root + "/platform/cusviews/complex/images/" + img,
"height" : 25,
"width" : 25,
"xoffset" : 0,
"yoffset" : 1,
'onClick' : function(p,e) {
if($.isFunction(p.onclick)){
p.onclick(p,e);
}
}
}
};
return Map.drawPoint(point);
}
function infoWindowStrategy(point){
var html = null;
var width = 0;
if(point.flag == "WZZY"){
var html = "<div class=\"tip_con\" style=\"width:260px;height:auto\">"+
" <div class=\"tip_tab tab_tipb\">"+
" 档案 "+
" <div class=\"turn\" style=\"display: block; opacity: 1;\">"+
" <div class=\"tip_table\">"+
"<table cellspacing='0' cellpadding='0' border='0'>" +
"<tr><td width='50'>名称:</td><td width='*'>"+(point.data.data.NAME||"")+"</td></tr>"+
"<tr><td width='50'>单位:</td><td width='*'>"+(point.data.data.ORG||"")+"</td></tr>" +
"<tr><td width='50'>地址:</td><td width='*'>"+(point.data.data.ADDRESS||"")+"</td></tr>" +
"<tr><td width='80'>坐标X(经度):</td><td width='*'>"+(point.data.data.PLACE_X||"")+"</td></tr>" +
"<tr><td width='80'>坐标Y(纬度):</td><td width='*'>"+(point.data.data.PLACE_Y||"")+"</td></tr>" +
"</table>"+
" </div>"+
" </div>"+
"</div>" +
"</div>";
}
return {"html":html,"width":280};
}
function openBasic(id){
var href = root + '/platform/views/StdListView.jsp?func=WELL&extWhere=and GL_GATEWELL_ID='+id;
showWindow("档案", href);
}
function clearMap(){
removePoint(gateWellPoints);
removePoint(illegalPlacePoints);
removePoint(exceptionPoints);
removePoint(userPoints);
removePoint(anodePilePoints);
removePoint(mashroomPoints);
cMap.removeLine(trajectoryLine);
$("#userCheckbox").attr("checked",false);
}
function removePoint(points){
for(var i=0; i < points.length; i++){
Map.removePoint(points[i]);
}
}
function showWindow(title,url){
windowView(title);
setTimeout(function(){
winFormDesigner.loadURL(url);
}, 0);
}
function windowView(title){
var options = {
modal : true,
title : title,
collapsible : false,
minimizable : false,
maximizable : false,
closable : true,
closed : false
};
var uid = "self_card_";
options["id"] = uid;
winFormDesigner = UIFactory.getUI(uid);
winFormDesigner = UIFactory.create(xpad.ui.Window, options);
var root = jQuery("body");
var offset = root.offset();
var winleft = 0;
var wintop = 0;
var newSize = {};
newSize["left"] = 0;
newSize["top"] = 0;
newSize["width"] = jQuery("body").width();
newSize["height"] = jQuery("body").height();
winFormDesigner.window("resize", newSize);
}
调用封装的全局方法,实现不同的业务
var point1 = {
'lng' : zbx,
'lat' : zby,
"flag":flag1,
"data":pdata,
'type' : {
'imgUrl' : root + "/platform/cusviews/complex/images/" + img,
"height" : 25,
"width" : 25,
"xoffset" : 0,
"yoffset" : 1
}
};
var content1 = infoWindowStrategy(point1);
var even={};
even.target={};
even.target.getPosition = function(){
return {lng:zbx, lat:zby,O:parseFloat(zbx)+(116.23146639084285-116.22542672247853),P:parseFloat(zby)+(39.815803909704194 - 39.81458279123017)};
}
var infoWindow1 = {content:content1.html, even:even};
Map.centerAt(zbx, zby);
Map.showInfoWindow(infoWindow1);
}
function playLine(){
var lineArr = [];
$.ajax({
type : "POST",
url : "/queryLine",
data : {'userId' : userId},
success : function(retData){
for(var i=0; i < retData[1].pointsKey.length; i++){
for(var j=0;j<retData[0][retData[1].pointsKey[i]].length;j++){
lineArr.push({'lng':retData[0][retData[1].pointsKey[i]][j].data.POINT_LNT, 'lat':retData[0][retData[1].pointsKey[i]][j].data.POINT_LAT});
}
Line.push(drowGjs(lineArr));
lineArr.length=0;
}
}
});
}
function drowGjs(dataList){
startPoints.push(drowPoint1(dataList[0].lng,dataList[0].lat,'qdzb.png',dataList[0],"",""));
endPoints.push(drowPoint1(dataList[dataList.length-1].lng,dataList[dataList.length-1].lat,"zb.png",dataList[dataList.length-1],"",""));
return drowLine(dataList, '#ff00cc');
}
$.ajax({
type : "POST",
url : getContextPath() + "/getChilds",
data : {"ids" : ids},
success : function(data) {
if (data) {
$.each(data,function(id,list){
var points = [];
for(var i=0;i < list.length; i++){
x = list[i].data.XLJCXX_DETAIL_ZBX;
y = list[i].data.XLJCXX_DETAIL_ZBY;
points.push({'lng' : y, 'lat' : x});
var mPoint = drowPoints(x, y, "QIU",id,list[i].data, function(point,e){
lineClick(point,e);
});
}
drowLine(points, lineClick);
});
}
}
});