高德地图web端js

下面是一些高德地图使用例子,自定义展示,右击拖动,搜索,画圆,定位等功能,没有整理仅供参考
var infoWindow = new AMap.InfoWindow({
							isCustom:true,//使用自定窗口0909;
							content: "<div style='width:330px;background-color: rgba(245,245,245,0.6);border: 1px solid #BCBCBC;box-shadow: 0 0 10px;border-radius:5px;'>" +
									"<p style='ine-height:15px; display:block;  color:#1a222c; z-index:9999;text-align:right;'><div  style='text-align:right;padding-top:5px;padding-right:10px;'class='info-top'><img onclick='javascript:window.Fsp.closewindow(\"" + _tvin + "\","+windowsArr.length+")' width='14' src='"+f.imgPathNew+"/close2.gif'/></div></p>" +
									"<p style='padding-left:20px;padding-right:20px; font-size:14px; line-height:34px; display:block; text-align:left; color:#1a222c; z-index:9999'>车架号:" + _tvin + "</p>" +
							    	"<p style='padding-left:20px;padding-right:20px; font-size:14px; line-height:34px; display:block; text-align:left; color:#1a222c; z-index:9999'>车牌:" + _tplateId + "</p>" +
							    	"<p style='padding-left:20px;padding-right:20px; font-size:14px; line-height:34px; display:block; text-align:left; color:#1a222c; z-index:9999'>使用人:" + _tdriver + "</p>" +
							    	"<p style='padding-left:20px;padding-right:20px; font-size:14px; line-height:34px; display:block; text-align:left; color:#1a222c; z-index:9999'>电话号码:" + _ttelephone + "</p>" +
							    	"<p style='padding-left:20px;padding-right:20px; font-size:14px; line-height:34px; display:block; text-align:left; color:#1a222c; z-index:9999'>速度:" + _tspeed + "km/h</p>" +
							    	"<p style='padding-left:20px;padding-right:20px; font-size:14px; line-height:34px; display:block; text-align:left; color:#1a222c; z-index:9999'>状态:" + _tsignOff + "</p>" +
							    	"<p style='padding-left:20px;padding-right:20px; font-size:14px; display:block; text-align:left; color:#1a222c; z-index:9999'>地址:" + _taddress + "</p>" +
							    	"<p style='padding-left:20px;padding-right:10px; font-size:14px; line-height:40px; display:block; text-align:left; color:#1a222c; z-index:9999'>定位时间:" + _tlocatedTimeText + "  " +
							    	"<span class='"+_tvin+"class' style='width:190px; height:30px; font-size:14px; background:#2b84ff;border-radius:3px;padding:5px;'><a id='"+_tvin+"ID' style='color:white;' href='javascript:window.Fsp.getmessage(\"" + _tvin + "\","+windowsArr.length+")'>手动定位</a></span></p>" +
							        mapstr+"<br/>" +
							        "</div><p style='padding-left:165px;padding-right:20px; font-size:14px; line-height:40px; display:block; text-align:left; color:#1a222c; z-index:9999'><img src='"+f.imgPathNew+"/sharp.png'/></p>",
							size:new AMap.Size(350, 400),
							autoMove:true,
							offset:new AMap.Pixel(0,-9)
						});


 
 
(function(f,$,w){
	var map,SosMap,page,currentOrder,zoom=15,placeSearch,IS_READ_ONLY_ENV,menu;
	var markerArr = new Array();
	var windowsArr = new Array();
	var locations = new Array();
	f.markerArr = markerArr;
	f.IS_READ_ONLY_ENV = IS_READ_ONLY_ENV;
	function _initMap(){
		map = new AMap.Map("mapContainer", {
			resizeEnable: true,
			zoom: 15
		});
		map.plugin(['AMap.ToolBar'], function() {
	        //设置地位标记为自定义标记
	        var toolBar = new AMap.ToolBar();
	        map.addControl(toolBar);
	        // 加载比例尺插件
	        map.plugin(["AMap.Scale"], function () {
	        	scale = new AMap.Scale();  
	            map.addControl(scale);  
	            scale.show();
	        });
	    });
		AMap.service(["AMap.Geocoder"], function() { //加载地理编码
	        geocoder = new AMap.Geocoder({
	            radius: 1000,
	            extensions: "all"
	        });
		});
		AMap.service(["AMap.PlaceSearch"], function() {
	        placeSearch = new AMap.PlaceSearch({ //构造地点查询类
	            pageSize: 10,
	            pageIndex: 1,
	            city: "全国", //城市
	            map: map,
	            panel:"result"
	        });
	        f.placeSearch = placeSearch;
	    });
	    AMap.plugin(['AMap.Autocomplete','AMap.PlaceSearch'],function(){
	        var autoOptions = {
	         // city: "全国", //城市,默认全国
	          input:'centeraddress'//使用联想输入的input的id
	        };
	        autocomplete= new AMap.Autocomplete(autoOptions);
	        var placeSearch = new AMap.PlaceSearch({
	              map:map
	        })
	        AMap.event.addListener(autocomplete, "select", function(e){
	           //TODO 针对选中的poi实现自己的功能
	           placeSearch.setCity(e.poi.adcode);
	           placeSearch.search(e.poi.name)
	        });
	      });
		
		f.menu=new ContextMenu(map);
		 function ContextMenu(map) {
		    var me = this;
	        this.mouseTool = new AMap.MouseTool(map); //地图中添加鼠标工具MouseTool插件
	        this.contextMenuPositon = null;
	        var content = "<div style='width:80px;height:30px;background-color:white;font-size:18px;color:red;border:1px solid red;'>" +
							"<center><a href='javascript:window.Fsp.setGeofence()'>设置围栏</a></center>" +
						   "</div>";
	
			this.contextMenu = new AMap.ContextMenu({isCustom: true, content:content});//通过content自定义右键菜单内容
			//地图绑定鼠标右击事件——弹出右键菜单
			map.on('rightclick', function(e) {
			    me.contextMenu.open(map, e.lnglat);
			    me.contextMenuPositon = e.lnglat; //右键菜单位置
			});
			
		   }
			
		//$("#mapContainer").height($(w).height()-150);
//		$('.wrap-small').height($(w).height()-70);
//		$('.map-wrap').height($(w).height()-70);
//		$("#mapContainer").height($(w).height()-70);
	}
	var closemark=function(){
		if(posMarker){
			 posMarker.setMap(null);
			 posMarker=undefined;
		 }
	}
	f.closemark=closemark;
	
	
	var setGeofence = function (){
	   f.menu.mouseTool.close();
	   var cnt = $('.check-dan:checked').length;
		if(cnt>0){
			var z=$('input[name="id"]:checked').parents('tr').attr('geostat');
			if(z!='4'){
				 if(posMarker){
					 posMarker.setMap(null);
					 posMarker=undefined;
				 }
					 posMarker = new AMap.Marker({
			 			map:map,
			            position:  f.menu.contextMenuPositon, //基点位置
			 			size: new AMap.Size(50, 66),
			 			offset:{x:-23,y:-72},
			 			icon: f.imgPathNew + "/chose-icon.png",
			            draggable: true,
			            cursor: 'move',
			            raiseOnDrag: true
			 		});
					 posMarker.on('rightclick', function(e) {
					      f.menu.contextMenu.open(map, e.lnglat);
					      f.menu.contextMenuPositon = e.lnglat; //右键菜单位置
					  });
			 		var DraggingMarker_Event = function(e){
			 			var lat = String(e.lnglat.lat);
			 			var lng = String(e.lnglat.lng);
			 			$("#latitude").val(lat);
			 			$("#longitude").val(lng)
			 			posMarker.setPosition(new AMap.LngLat(lng,lat));
			 			var address = "";
			 			geocoder.getAddress([lng, lat], function(status, result) {
			 		        if (status === 'complete' && result.info === 'OK') {
			 		           //获得了有效的地址信息:
			 		        	address = result.regeocode.formattedAddress;
			 		        }else{
			 		        	address = '';
			 		        }
			 		        $('#latitude').val(lat);
			 		        $('#longitude').val(lng);
			 				$("#centeraddress").val(address);
			 		    });
			 		}
			 		geocoder.getAddress(f.menu.contextMenuPositon, function(status, result) {
		 		        if (status === 'complete' && result.info === 'OK') {
		 		        	address = result.regeocode.formattedAddress;
		 		        }else{
		 		        	address = '';
		 		        }
		 		        $('#latitude').val(f.menu.contextMenuPositon.lat);
		 		        $('#longitude').val(f.menu.contextMenuPositon.lng);
		 				$("#centeraddress").val(address);
		 		    });
			 		AMap.event.addListener(posMarker, 'dragging', DraggingMarker_Event);
			}
		}
			f.menu.contextMenu.close();
		
	}
	f.setGeofence=setGeofence;
	
	var _SosMap = function(){
		var marker;
		var clearMap = this.clearMap=function(){
			marker?marker.setMap(null):!1;
		}
		var clearMaps = this.clearMaps=function(){
			$.each(markerArr, function(i, mk){  
				mk?mk.setMap(null):!1;
			});
			markerArr.length = 0;
		}
		this.setVehicleLocations=function(locations){
			clearMaps();
			$.each(locations, function(i, posObj){
				addmarker(i, posObj);
			});
			map.setFitView();
		}
		this.setGeofenceCircles=function(locations){
			map.clearMap();
			$.each(locations, function(i, posObj){
				addcircle(i, posObj);
			});
			map.setFitView();
		}
	}
	SosMap=f.SosMap = new _SosMap();
	//添加marker&infowindow
	function addmarker(i, posObj) {
	  if(posObj != undefined){
		var lngX = posObj.lon;
		var latY = posObj.lat;
		var Close_Windows = function () {
			//
		};
		if(lngX != 0 && latY !=0 && lngX != 515 && latY != 515) {
			var mar = new AMap.Marker({
				map:map,
				size: new AMap.Size(50, 50),
				position:new AMap.LngLat(lngX, latY),
				offset:{x:-18,y:-24},
				extData:{"geostatus":posObj.geostatus,"vin":posObj.vin},
				topWhenMouseOver:true
			});
			
			markerArr.push(mar);
			if(posObj.geostatus == 0) {//出圈
				mar.setIcon(f.imgPathNew + "/red_s_" + (i+1) + ".png");
			} else if(posObj.geostatus == 1) {//未出圈
				mar.setIcon(f.imgPathNew + "/green_" + (i+1) + ".png");
			} else {//未设置
				mar.setIcon(f.imgPathNew + "/blue_" + (i+1) + ".png");
			}
			var MouseOver_CallBack = function (e) {
				mar.setIcon(f.imgPathNew + "/red_b_" + (i+1) + ".png");
				mar.setzIndex(300);
			};
			
			var MouseOut_CallBack = function (e) {
				var obj = 1;
				if("undefined" != typeof e.target.G){
					obj=e.target.G.extData.geostatus;
				}
				if("undefined" != typeof e.target.H){
					obj=e.target.H.extData.geostatus;
				}
				if(obj == 0) {
					mar.setIcon(f.imgPathNew + "/red_s_" + (i+1) + ".png");
				} else if(obj == 1) {
					mar.setIcon(f.imgPathNew + "/green_" + (i+1) + ".png");
				} else {
					mar.setIcon(f.imgPathNew + "/blue_" + (i+1) + ".png");
				}
				mar.setzIndex(100);
			};
			mar.on('rightclick', function(e) {
				 f.menu.contextMenu.open(map, e.lnglat);
				 f.menu.contextMenuPositon  = e.lnglat; //右键菜单位置
			});
			
			//电子围栏选中事件
			var MouseClick_CallBack = function (e) {
				$('.check-dan').each(function(i, item){
					$(item).removeAttr('disabled');
				})
				
				index_shezhi = 0;
				map.setCenter(mar.getPosition());
				$('.erro-info').css('color','#fafafa');
				enableSetGeofenceBtn();
				var cnt = 0;
				var plate_Id = "";
				var lat_ = "";
				var lon_ = "";
				var addr_ = "";
				var phone_ = "";
				var isalert_ = "";
				var radius_ = "";
				var geostatus_s=trim_($(this).attr("geostat"));
				if(geostatus_s=='4'){
					$('.off').prop('checked',true);
					$('.onn').prop('checked',false);
					$('.set-sel').css('color','#b4b4b4').prop('disabled',true);
					$('#clo-set').addClass('active').click(function(){
						$('.set-box').hide();
						btnOpen();
					});
					$('#setGeofence').prop('disabled',true).css('background','#b4b4b4');
					$('.xiugai-btn').css('display','none');
					$('.xgbtnj').css('display','');
					$('.map-click').css('opacity',.5);
					$('.remind-btn').css({"display":"none"});
					$('#alertphone').prop('disabled',true);
					$('input[name="baojing"]').prop('disabled',true);
					if(posMarker !=undefined){
						posMarker.setMap(null);
						posMarker=undefined;
					}
					v=1;
					
				}else{
					$('#setGeofence').prop('disabled',false).css('background','#2b84ff');
					$('#clo-set').removeClass('active').click(function(){
						$('.set-box').show();
					});
					$('.set-sel').css('color','#000').prop('disabled',false);
					$('.off').prop('checked',false);
					$('.onn').prop('checked',true);
					$('.xiugai-btn').css('display','');
					$('.xgbtnj').css('display','none');
					$('.map-click').css('opacity',1);
					$('.remind-btn').css({"display":"none"});
					$('#alertphone').prop('disabled',true);
					$('input[name="baojing"]').prop('disabled',true);
					v=0;
					
				}
				
				var t = $(".table2 tbody tr .check-dan").eq(i)[0];
				if(e.toElement.type != 'checkbox' && ($(t).attr("disabled") != 'disabled')) {
					if($(t).is(':checked')) {
						$(t).removeAttr('checked');
					} else {
						$(t).prop('checked','true');
					}
				}
				var rslt = $(t).is(':checked');
				if(rslt) {
					$('.check-dan').each(function(ts, item0){
						$(item0).removeAttr('disabled');
					})
					$(".table2 tbody tr").eq(i).css('background','#e7eaee');
					mar.setIcon(f.imgPathNew + "/red_b_" + (i+1) + ".png");
					mar.setzIndex(300);
				} else {
					$(".table2 tbody tr").eq(i).css('background','#fafafa');
					if(posObj.geostatus == 0) {
						mar.setIcon(f.imgPathNew + "/red_s_" + (i+1) + ".png");
					} else if(posObj.geostatus == 1) {
						mar.setIcon(f.imgPathNew + "/green_" + (i+1) + ".png");
					} else {
						mar.setIcon(f.imgPathNew + "/blue_" + (i+1) + ".png");
					}
					mar.setzIndex(100);
				}
				//$('.enclosure .position .check-dan:checked').length;
				$('.check-dan').each(function(i, item){
					if($(item).is(':checked')) {
						cnt ++;
						if(cnt == 1) {
							plate_Id = $(this).attr("plateId");
							lat_ = trim_($(this).attr("lat"));
							lon_ = trim_($(this).attr("lon"));
							var lnglatXY = [lon_, lat_]; 
							geocoder.getAddress(lnglatXY, function(status, result) {
					            if (status == 'complete' && result.info == 'OK') {
					            	addr_ = result.regeocode.formattedAddress;
					            } else {
					            	addr_ = '';
					            }
								$("#centeraddress").val(addr_);
								$("#centeraddress_old").val(addr_);
							});
							phone_ = trim_($(this).attr("phone"));
							isalert_ = trim_($(this).attr("isalert"));
							radius_ = trim_($(this).attr("radius"));
							
						}
					}
				})
				if(cnt >= 1) {
					if('null'==plate_Id){
						$("#plateId").html('');
					}else{
						$("#plateId").html(plate_Id);
					}
					$("#plateId").html(plate_Id);
					$("#latitude").val(lat_);
					$("#longitude").val(lon_);
					$("#radius").val(radius_);
					$("#radius_old").val(radius_);
					$("#alertphone").val(phone_);
					$('input[name="baojing"]').each(function(l, it) {
						if(isalert_) {
							if($(it).val() == isalert_) {
								$(it).prop('checked','true');
							} else {
								$(it).removeAttr('checked');
							}
						} else {
							if($(it).val() == 1) {
								$(it).prop('checked','true');
							} else {
								$(it).removeAttr('checked');
							}
						}
					});
					$('.enclosure .right .tbl a').eq(index_shezhi).addClass('active').css('background','#2b84ff').siblings().removeClass('active').css('background','#fafafa');
					$('.tbl-right').hide().eq(index_shezhi).show();
					$('.enclosure .right .tbl i').hide();
				}
		//--------------------------------
				var selectStatusVal=$("#geopgstate").val();//状态值
				var selectAllCurrent=$("#selectall").val();//是否全选或当页

				//	if(selectAllCurrent==''&&selectStatusVal==''){//所有的单个选择 默认状态所有
				if(selectAllCurrent==''){//没有选择全选所有或当页,只能单个选
					if($('input[name="id"]:checked').length>1){//选中1个以上
						if(tableCheckValue.length>0){
							for(var ki=0;ki<tableCheckValue.length;ki++){
								$('input[name="id"]:checked').each(function(){
									if($(this).val()==tableCheckValue[ki]){
										this.checked=false;
										$(this).parents('tr').css('background','#fafafa');
										//$(this).css('background','#fafafa');
									}
				                });
							}
							tableCheckValue.length=0;
						}
					}else{
						tableCheckValue.length=0;
					}
					$('input[name="id"]:checked').each(function(){
						var sv=$(this).val();
						tableCheckValue.push(sv);
					});
				}
				if(selectAllCurrent=='0'&&selectStatusVal!=''){
					//点击选中时,看值是否在未选中的里面
					$('input[name="id"]:not(:checked)').each(function(){
						selectAllNoCheckValue.push($(this).val());
					})
					selectAllNoCheckValue=uniQueue(selectAllNoCheckValue);
					$('input[name="id"]:checked').each(function(){
						var selectv=$(this).val();
						var sn = selectAllNoCheckValue.indexOf(selectv);
						if(sn!=-1){
							selectAllNoCheckValue.splice(sn,1);
						}
					})
					//alert(selectAllNoCheckValue.length);
				}
				
				
				if(cnt == 1){
					if(!window.Fsp.IS_READ_ONLY_ENV) {
						//setGeofenceInfoNoValide();
					}
				}
				if(cnt > 1){
					$("#plateId").html("查看已选车辆");
				}
				if(cnt < 1){
					disableSetGeofenceBtn();
					$("#latitude").val("");
					$("#longitude").val("");
					$("#centeraddress").val("");
					$("#centeraddress_old").val("");
					$("#radius").val("");
					$("#radius_old").val("");
					$("#alertphone").val("");
					$('.enclosure .right .tbl a').eq(0).removeClass('active').css('background','#ACA7A7').siblings().css('background','#fafafa');
					$('.enclosure .right .tbl a').eq(1).removeClass('active').css('background','#fafafa').siblings().css('background','#ACA7A7');
					$('.enclosure .right .tbl-right').hide();
					//$('.enclosure .right .tbl i').show();
				}
				
			};
			
			$(".table2 tbody tr").eq(i).bind("click", MouseClick_CallBack);
			//$(".table2 tbody tr .check-dan").eq(i).bind("mouseover", MouseOver_CallBack);
			//$(".table2 tbody tr").eq(i).bind("mouseout", MouseOut_CallBack);
			AMap.event.addListener(mar, "mouseover", MouseOver_CallBack);
			AMap.event.addListener(mar, "mouseout", MouseOut_CallBack);
		} else {
			
			$(".table2 tbody tr").eq(i).bind("mouseover", Close_Windows);
			$(".table2 tbody tr").eq(i).bind("mouseout", Close_Windows);
		}
	}
	}
	
	function addcircle(i, posObj) {
		if(posObj.longitude && posObj.latitude && posObj.radius) {
			var lngX = posObj.longitude;
			var latY = posObj.latitude;
			var radius_ = posObj.radius ;
			if(radius_.indexOf("KM") > 0) {
				radius_ = posObj.radius.replace("KM","");
				radius_ = radius_ * 1000;
				var circle = new AMap.Circle({
			        center: new AMap.LngLat(lngX, latY),// 圆心位置
			        radius: radius_, //半径
			        strokeColor: "#2B84FF", //线颜色
			        strokeOpacity: 1, //线透明度
			        strokeWeight: 1, //线粗细度
			        fillColor: "#2B84FF", //填充颜色
			        fillOpacity: 0.28//填充透明度
			    });
				circle.on('rightclick', function(e) {
				      f.menu.contextMenu.open(map, e.lnglat);
				      f.menu.contextMenuPositon = e.lnglat; //右键菜单位置
				  });
			    circle.setMap(map);
			}
		}
	}
	
	function refreshDBGeoStatus_noGeofenceInterface() {
		if($("#geopgstate").val()==''){//没有选择状态  允许 刷新
		  $.ajax({url:f.locationPath+"/getRestAllVehicleBind?t="+new Date().getTime(),async:true }).done(function(data) {
			if(data.length>0){
				$.each(data, function(i, item){
					$.ajax({url:f.locationPath+"/getLocationByVin?t="+new Date().getTime(),async:true,data: {"vin":item.vin} }).done(function(data) {
						if(data&&(data.code=='E0000'||data.code=='0000')){
							if(data.data&&data.data.length>0){
								var posObj = data.data[0];
								if(parseInt(posObj.lat)!=515||parseInt(posObj.lon)!=515){
									if(!isNull_(item.longitude) && !isNull_(item.latitude) && !isNull_(item.radius)) {
										var radius_t = item.radius;
										if(radius_t.indexOf("KM") > 0) {
											radius_t = radius_t.replace("KM", "");
											radius_t = radius_t*1000;
											var circle = new AMap.Circle({
										        center: new AMap.LngLat(item.longitude, item.latitude),// 圆心位置
										        radius: radius_t
										    });
											var geostatus = 2;//未设置
											if(circle.contains(new AMap.LngLat(posObj.lon, posObj.lat))) {
												geostatus = 1;//未出圈
											} else {
												geostatus = 0;//出圈
											}
											//$.ajax({url:f.locationPath+"/updateGeoFenceStatus?t="+new Date().getTime(),async:true,data: {"id":item.id, "geostatus":geostatus} });
										}
									}/* else {
										$.ajax({url:f.locationPath+"/updateGeoFenceStatus?t="+new Date().getTime(),async:true,data: {"id":item.id, "geostatus":2} });
									}*/
								}/* else {
									$.ajax({url:f.locationPath+"/updateGeoFenceStatus?t="+new Date().getTime(),async:true,data: {"id":item.id, "geostatus":2} });
								}*/
							}/* else {
								$.ajax({url:f.locationPath+"/updateGeoFenceStatus?t="+new Date().getTime(),async:true,data: {"id":item.id, "geostatus":2} });
							}*/
						} /*else {
							$.ajax({url:f.locationPath+"/updateGeoFenceStatus?t="+new Date().getTime(),async:true,data: {"id":item.id, "geostatus":2} });
						}*/
					});
				});
			}
		});
		$(".btn3").click();
	  }
	}
	f.refreshDBGeoStatus_noGeofenceInterface = refreshDBGeoStatus_noGeofenceInterface;
	
	function refreshDBGeoStatus() {
		$.ajax({url:f.locationPath+"/getRestAllVehicleBind?t="+new Date().getTime(),async:true }).done(function(rslt) {
			if(rslt.length>0){
				$.each(rslt, function(i, item){
					$.ajax({url:f.locationPath+"/getGeofenceStatus?t="+new Date().getTime(),async:true,data: {"vin":item.vin} }).done(function(data) {
						if(data&&(data.code=='E0000'||data.code=='0000')){
							if(data.body&&data.body.length>0){
								var posObj = data.body[0];
								var geostatus = 1;
								if(!isNull_(posObj.securityStatus)){
									if(posObj.securityStatus == 'IN') {//未出圈
										geostatus = 1;
									} else if(posObj.securityStatus == 'OUT') {//出圈
										geostatus = 0;
									}
									//$.ajax({url:f.locationPath+"/updateGeoFenceStatus?t="+new Date().getTime(),async:false,data: {"id":item.id, "geostatus":geostatus} });
								}
							}
						}
					});
				});
			}
		});
		$(".btn3").click();
	}
	f.refreshDBGeoStatus = refreshDBGeoStatus;
	
	function refreshCurrentPageGeoStatus() {
		$("input[type='checkbox']").each(function(i, item){
			var vin = $(item).attr("vin");
			$.ajax({url:f.locationPath+"/getLocationByVin?t="+new Date().getTime(),async:false,data: {"vin":vin} }).done(function(data) {
				if(data&&(data.code=='E0000'||data.code=='0000')){
					if(data.data&&data.data.length>0){
						var posObj = data.data[0];
						if(parseInt(posObj.lat)!=515||parseInt(posObj.lon)!=515){
							if(item.longitude && item.latitude && item.radius) {
								var radius_t = item.radius;
								if(radius_t.indexOf("KM") > 0) {
									radius_t = radius_t.replace("KM", "");
									radius_t = radius_t*1000;
									var circle = new AMap.Circle({
								        center: new AMap.LngLat(item.longitude, item.latitude),// 圆心位置
								        radius: radius_t
								    });
									var geostatus = 0;
									if(circle.contains(new AMap.LngLat(posObj.lon, posObj.lat))) {//未出圈
										geostatus = 1;
									} else {//出圈
										geostatus = 0;
									}
//									$.ajax({url:f.locationPath+"/updateGeoFenceStatus?t="+new Date().getTime(),async:false,data: {"id":item.id, "geostatus":geostatus} });
								}
							}
						}
					}
				}
			});
		});
	}
	f.refreshCurrentPageGeoStatus = refreshCurrentPageGeoStatus;
	
	function addResultEvent(){
	}

	function trim_(obj) {
		if(obj == "" || obj == "null" || obj == null || obj == undefined) {
			return '';
		} else {
			return obj;
		}
	}
	f.trim_ = trim_;

	function isNull_(obj) {
		if(obj == "" || obj == "null" || obj == null || obj == undefined) {
			return true;
		} else {
			return false;
		}
	}
	f.isNull_ = isNull_;
	
	
	var localdirectg = function() {
		disableSetGeofenceBtn();
		chageCurrentPageGeostatus();
		if(locations.length > 0) {
			SosMap.setVehicleLocations(locations);
		}
		$("input[type='checkbox']").each(function(i, item){
			if(i==0) {
				var first_plateId = $(item).attr("plateId");
				if('null'==first_plateId){
					$("#plateId").html('');
				}else{
					$("#plateId").html(first_plateId);
				}
				
			}
		});
	}
	f.localdirectg = localdirectg;
	
	var chageCurrentPageGeostatus = function() {
		locations.length = 0;
		$('.check-dan').each(function(i, item){
			var vin_ = $(".table2 tbody tr").eq(i).attr("vin");
			var longitude = $(this).attr("lon");
			var latitude = $(this).attr("lat");
			var radius = $(this).attr("radius");
			$.ajax({url:f.locationPath+"/getLocationByVin?t="+new Date().getTime(),async:false,data: {"vin":vin_} }).done(function(data) {
				if(data&&(data.code=='E0000'||data.code=='0000')){
					var posObj = data.data[0];
					if(data.data&&data.data.length>0){
						if(parseInt(posObj.lat)!=515||parseInt(posObj.lon)!=515){
							if(radius.indexOf("KM") > 0) {
								var radius_t = radius.replace("KM", "");
								radius_t = radius_t*1000;
								if('null'==longitude){
									longitude=0;
								}
								if('null'==latitude){
									latitude=0;
								}
								var circle = new AMap.Circle({
							        center: new AMap.LngLat(longitude, latitude),// 圆心位置
							        radius: radius_t
							    });
								var geostatus = 2;
								if(circle.contains(new AMap.LngLat(posObj.lon, posObj.lat))) {//未出圈
									geostatus = 1;
									$(this).parent().prev().find("a").html("未出圈");
									$(this).parent().prev().find("a").addClass('no_chuquan').removeClass('chuquan').removeClass('no_set');
								} else {//出圈
									geostatus = 0;
									$(this).parent().prev().find("a").html("出圈");
									$(this).parent().prev().find("a").addClass('chuquan').removeClass('no_chuquan').removeClass('no_set');
								}
								if(geostatus == 2) {
									$(this).parent().prev().find("a").html("未设置");
									$(this).parent().prev().find("a").addClass('no_set').removeClass('chuquan').removeClass('no_chuquan');
								}
								//$(".table2 tbody tr").eq(i).attr("geostat", geostatus);
								posObj.geostatus = geostatus;
							}
						}
						
					}
					locations.push(posObj);
				}else{
					locations.push(posObj);
				}
			});
		});
	}
	f.chageCurrentPageGeostatus = chageCurrentPageGeostatus;
	
	
	var detail_vin ;
	var _Timer = function(vin){
		var time = 120000,timer,vin_ = vin,ele_,t = timer,scheduler=this;
		this.setVin=function(vin){
			vin_=vin;
		}
		this.setEle=function(ele){
			ele_=ele;
		}
		function run(){
			f.currentVin = vin_;
			if(!f.currentVin){
				t.stop();
				return;
			}
			var i=0;
			$(".tingzhu").each(function(){
				$.ajax({url:f.locationPath+"/getRestVehicleBind?t="+new Date().getTime(),async:false,data: {"vin":""} }).done(function(data) {
					var content = data.pageResult.content;
					if(content.length>0){
						SosMap.setVehicleLocations(content);
					}
				});
			});
		}
		this.start=function(){
			if(timer){
				this.stop();
			}
			run();
			timer = w.setInterval(run, time);
		}
		this.stop=function(){
			if(timer){
				w.clearInterval(timer);
				timer=null;
			}
		}
	}
	var timer = f.monitorTimer = new _Timer();
	
	$("#radius").bind("change", function(){
		$('.erro-info').css('color','#fafafa');
		var cnt = $('.check-dan:checked').length;
		if(cnt >= 1) {
			enableSetGeofenceBtn();
		}
	});
	
	//点击地图锚点
    var posMarker = undefined;
    $(".map-click").bind("click",function(e){
		$('.erro-info').css('color','#fafafa');
		var cnt = $('.check-dan:checked').length;
		if(cnt>0){
			var z=$('input[name="id"]:checked').parents('tr').attr('geostat');
			if(z!='4'){
				if(cnt >= 1) {
					enableSetGeofenceBtn();
				}
		    	if(posMarker) {
		    		
		    	} else {
		        	posMarker = new AMap.Marker({
		    			map:map,
		                position: map.getCenter(),
		    			size: new AMap.Size(50, 66),
		    			offset:{x:-23,y:-72},
		    			icon: f.imgPathNew + "/chose-icon.png",
		                draggable: true,
		                cursor: 'move',
		                raiseOnDrag: true
		    		});
		    		var DraggingMarker_Event = function(e){
		    			//var lat = String(e.lnglat.I);
		    			//lat = lat.substring(0,10);
		    			//var lng = String(e.lnglat.D);
		    			// = lng.substring(0,10);
		    			var lat = String(e.lnglat.lat);
		    			var lng = String(e.lnglat.lng);
		    			$("#latitude").val(lat);
		    			$("#longitude").val(lng)
		    			posMarker.setPosition(new AMap.LngLat(lng,lat));
		    			var address = "";
		    			geocoder.getAddress([lng, lat], function(status, result) {
		    		        if (status === 'complete' && result.info === 'OK') {
		    		           //获得了有效的地址信息:
		    		        	address = result.regeocode.formattedAddress;
		    		        }else{
		    		        	address = '';
		    		        }
		    				$("#centeraddress").val(address);
		    		    });
		    		}
		    		geocoder.getAddress(map.getCenter(), function(status, result) {
		 		        if (status === 'complete' && result.info === 'OK') {
		 		        	address = result.regeocode.formattedAddress;
		 		        }else{
		 		        	address = '';
		 		        }
		 				$("#centeraddress").val(address);
		 		    });
		    		
		    		AMap.event.addListener(posMarker, 'dragging', DraggingMarker_Event);
		    	}
			}
		}
		
	});
	
	//$(".search_position").bind("click",function(){
    f.confirmSubmit=function	confirmSubmit(){
    	var addr = $("#centeraddress").val();
        var t = placeSearch.search(addr);
        return false;
	}
	//});
	
	function enableSetGeofenceBtn() {
		$('#setGeofence').css('background','#2b84ff');
		$('#setGeofence').removeAttr('disabled');
	}
	function disableSetGeofenceBtn() {
		closemark();
		$('#setGeofence').css('background','#ACA7A7');
		$('#setGeofence').attr('disabled',true);
	}
	
	$("#centeraddress").bind("keydown", function(){
		$('.erro-info').css('color','#fafafa');
		var cnt = 0;
		$('.check-dan').each(function(i, item){
			if($(item).is(':checked')) {
				cnt ++;
			}
		});
		if(cnt >= 1) {
			enableSetGeofenceBtn();
		}
	});
	
	function changeCheckedGeostat(longitude, latitude, radius) {
		$('.check-dan').each(function(i, item){
			if($(item).is(':checked')) {
				var vin_ = $(".table2 tbody tr").eq(i).attr("vin");
				$.ajax({url:f.locationPath+"/getLocationByVin?t="+new Date().getTime(),async:false,data: {"vin":vin_} }).done(function(data) {
					if(data&&(data.code=='E0000'||data.code=='0000')){
						if(data.data&&data.data.length>0){
							var posObj = data.data[0];
							if(parseInt(posObj.lat)!=515||parseInt(posObj.lon)!=515){
								if(radius.indexOf("KM") > 0) {
									var radius_t = radius.replace("KM", "");
									radius_t = radius_t*1000;
									var circle = new AMap.Circle({
								        center: new AMap.LngLat(longitude, latitude),// 圆心位置
								        radius: radius_t
								    });
									var geostatus = 2;
									if(circle.contains(new AMap.LngLat(posObj.lon, posObj.lat))) {//未出圈
										geostatus = 1;
									} else {//出圈
										geostatus = 0;
									}
									$(".table2 tbody tr").eq(i).attr("geostat", geostatus);
								}
							}
						}
					}
				});
			}
		});
	}
	
	function displayValue(cnt) {
		if(cnt >= 1) {
			if('null'==plate_Id){
				$("#plateId").html('');
			}else{
				$("#plateId").html(plate_Id);
			}
			$("#latitude").val(lat_);
			$("#longitude").val(lon_);
			$("#radius").val(radius_);
			$("#radius_old").val(radius_);
			$("#alertphone").val(phone_);
			$('input[name="baojing"]').each(function(l, it) {
				if(isalert_) {
					if($(it).val() == isalert_) {
						$(it).prop('checked','true');
					} else {
						$(it).removeAttr('checked');
					}
				} else {
					if($(it).val() == 1) {
						$(it).prop('checked','true');
					} else {
						$(it).removeAttr('checked');
					}
				}
			});
		}
		if(cnt < 1){
			disableSetGeofenceBtn();
			$("#latitude").val("");
			$("#longitude").val("");
			$("#centeraddress").val("");
			$("#centeraddress_old").val("");
			$("#radius").val("");
			$("#radius_old").val("");
			$("#alertphone").val("");
		}
	}
	
	/*$("#setGeofenceMenu").bind("click",function(e){
		//index_shezhi = 1;
		$('.check-dan').each(function(i, item){
			$(item).removeAttr('disabled');
		});
		var cnt = 0;
		var plate_Id = "";
		var lat_ = "";
		var lon_ = "";
		var addr_ = "";
		var phone_ = "";
		var isalert_ = "";
		var radius_ = "";
		$('.check-dan').each(function(i, item){
			if($(item).is(':checked')) {
				cnt ++;
				if(cnt == 1) {
					plate_Id = $(this).attr("plateId");
					lat_ = trim_($(this).attr("lat"));
					lon_ = trim_($(this).attr("lon"));
					var lnglatXY = [lon_, lat_]; 
					geocoder.getAddress(lnglatXY, function(status, result) {
			            if (status == 'complete' && result.info == 'OK') {
			            	addr_ = result.regeocode.formattedAddress;
			            } else {
			            	addr_ = '';
			            }
						$("#centeraddress").val(addr_);
						$("#centeraddress_old").val(addr_);
					});
					phone_ = trim_($(this).attr("phone"));
					isalert_ = trim_($(this).attr("isalert"));
					radius_ = trim_($(this).attr("radius"));
				}
			}
		});
		displayValue(cnt);
		if(index_shezhi == 1) {
			if(cnt >= 1) {
				$('.enclosure .right .tbl a').eq(index_shezhi).addClass('active').css('background','#fafafa').siblings().removeClass('active').css('background','#2b84ff');
			}
			if(cnt < 1){
				index_shezhi = 0;
			}
		} else {
			if(cnt >= 1) {
				$('.enclosure .right .tbl a').eq(index_shezhi).addClass('active').css('background','#2b84ff').siblings().removeClass('active').css('background','#fafafa');
			}
			if(cnt < 1){
				index_shezhi = 1;
			}
		}
		$('.enclosure .right .tbl a').eq(index_shezhi).addClass('active').css('background','#ACA7A7').siblings().removeClass('active').css('background','#fafafa');
		$('.enclosure .right .tbl-right').hide();
		$('.enclosure .right .tbl i').show();
	});*/
	
	$("#setGeofence").bind("click",function(e){
		var centeraddress = $("#centeraddress").val();
		var centeraddress_old = $("#centeraddress_old").val();
		var latitude = $("#latitude").val();
		var longitude = $("#longitude").val();
		var radius = $("#radius").val();
		var radius_old = $("#radius_old").val();
		var geostatus_old = $("#geostatus_old").val();
		changeCheckedGeostat(longitude, latitude, radius);
		var chk_values =[];
		var geostatus_values =[];
		$('.check-dan').each(function(i, item){
			if($(item).is(':checked')) {
				chk_values.push($(this).val());
				geostatus_values.push($(".table2 tbody tr").eq(i).attr("geostat"));
			}
		});
		var isall=$("#selectall").val();
		var selectStatus=$("#geopgstate").val();
		var data = {
			"id":chk_values,
			"address":centeraddress,
			"latitude":latitude,
			"longitude":longitude,
			"geostatus":geostatus_values,
			"radius":radius,
			"isall":isall,
			"selectstatus":selectStatus,
			"cancelvalue":selectAllNoCheckValue.toString()
		};
		if(centeraddress == centeraddress_old && radius_old == radius) {
			$('#tipinfo').html("围栏信息没有修改,请您修改后再保存");
			$('.erro-info').css('color','red');
		} else {
			if(chk_values.length==0 || isNull_(centeraddress) || isNull_(latitude) || isNull_(longitude) || isNull_(radius)) {
				if(isNull_(latitude) || isNull_(longitude)) {
					$('#tipinfo').html("围栏经纬度没定位");
				}
				if(isNull_(centeraddress)) {
					$('#tipinfo').html("围栏地址没填");
				}
				$('.erro-info').css('color','red');
				disableSetGeofenceBtn();
			} else {
				
				
				$.ajax({url:f.locationPath+"/setGeofenceInfo?t="+new Date().getTime(), async:false, data:data }).done(function(data) {
					$("form[name=fm]").attr("action","showVehicleBindJson").submit();
					$('.enclosure .right .tbl a').eq(0).removeClass('active').css('background','#ACA7A7').siblings().css('background','#fafafa');
					$('.enclosure .right .tbl a').eq(1).removeClass('active').css('background','#fafafa').siblings().css('background','#ACA7A7');
					$('.enclosure .right .tbl-right').hide();
					posMarker = undefined;
				});
			}
		}
	});
	
	$(".remind-btn").bind("click",function(e){
		var chk_values =[];
		$('input[name="id"]:checked').each(function(){
			if($(this).attr("disabled") == undefined || $(this).attr("disabled") != "disabled") {
				chk_values.push($(this).val());
			}    
		});
		if(chk_values.length > 0) {
			var alertphone = $("#alertphone").val();
			var isalert = $('input[name="baojing"]:checked').val();
			var latitude = $("#latitude").val();
			var longitude = $("#longitude").val();
			var radius = $("#radius").val();

			var isall=$("#selectall").val();
			var selectStatus=$("#geopgstate").val();
			var data = {
				"id":chk_values,
				"alertphone":alertphone,
				"latitude":latitude,
				"longitude":longitude,
				"radius":radius,
				"isalert":isalert,
				"isall":isall,
				"selectstatus":selectStatus,
				"cancelvalue":selectAllNoCheckValue.toString()
			};
			$.ajax({url:f.locationPath+"/setGeofenceAlert?t="+new Date().getTime(), async:false, data:data }).done(function(data) {
				$('.check-dan').each(function(i, item){
					if($(item).is(':checked')) {
						$(this).attr("isalert", isalert);
						$(this).attr("phone", alertphone);
					}
				})
			});
		}
	});
	
	
	function _initAutoComplete(){
		var searchbox = $( "#searchbox" );
		var val = searchbox.val();
		searchbox.autocomplete({
			source: function(request,response){
				if(request.term.length<1){
					return;
				}
				var reqBody = {keyword:request.term};
				reqBody[f.Csrf.parameterName] = f.Csrf.token;
				$.post(f.vehiclePath+"/autoComplete?t="+new Date().getTime(),reqBody,function(data){
					response(data);
				});
			}
		});
	}
	
	function showSignOffLocation(vin){
		window.open(f.locationPath+"/getLocationHistoryByVin?vin="+vin);
		//f.popup.open(f.locationPath+"/getLocationHistoryByVin?vin="+vin+"&t="+new Date().getTime());
	}
	
	function addVehicleDetailsEvent(){
		$("#tingzhu0 [vin]").each(function(){
			$(this).click(function(){
				showSignOffLocation($(this).attr("vin"));
				return !1;
			});
		});
	}
	
	function getLocationByVin(vin,ele){
		timer.setVin(vin);
		timer.setEle(ele);
		timer.start();
	}
	
	function addEnterEvent(){
		$("form").bind("keydown",function(e){
			e=e||window.event;
			var key = e.which||e.keycode;
	            if (key == 13) {
	            		$(this).submit();
	            }
		});
		function searchVehicleCallback(tmpl,obj,pageHtml){
			var rsHtml = tmpl.html(obj.page);
			var body = rsHtml+pageHtml;
			if(obj.page.totalElements < 1) {
				$("#tbody").html("");
			} else {
				$("#tbody").html(body);
			}
			$("#geofencepage").html(pageHtml);
			if(!$(".arrow").hasClass('current')){
				$(".arrow").click();
			}
		}
		function searchVehicle(data){
			var pageJson = f.Util.castPage(data);
			pageJson.type = "simple";
			if(!f.Pages.hasPage("defaultPage")){
				page = f.Pages.addPage(pageJson,"defaultPage");
				registerSetPage();
			}else{
				page = f.Pages.getPage("defaultPage");
				page.binding(pageJson);
			}
			var pageHtml = page.html();
			f.Jqote2.get("geofence",function(tpl,tmpl,jqote){
				searchVehicleCallback(tmpl,page,pageHtml);
				page.referesh();
				addResultEvent();
				addOrderEvent();
			});
		}
		$("form").submit(function(){
			var reqBody =$(this).serialize();
				$.post(this.action+"?t="+new Date().getTime(),reqBody,function(data){
					searchVehicle(data);
					var content = data.pageResult.content;
					if(content.length > 0) {
						SosMap.setGeofenceCircles(content);
						//chageCurrentPageGeostatus();
						localdirectg();
					}else{
						$('#plateId').html('');
					}
					
					var selectStatusVal=$("#selectall").val();
					if(selectStatusVal=='1'){//选中当页 
						if(selectCurrPageValue.length==0){
							$("input[name='id']").prop("checked",true);
							$('input[name="id"]:checked').each(function(){
								selectCurrPageValue.push($(this).val());
								$(this).parents('tr').css('background','#fafafa');
							})
							$('input[name="id"]:checked').each(function(){
								$(this).trigger("click");
								$(this).trigger("click");
								return false;
							})
					  }else{
						  selectCurrPageValue.length==0
						  selectCurrPageValue.length=11;
						 /// selectCurrPageValue.length=11;
					  }
					}
					
					if(selectStatusVal=='0'){//选中所有(也是当页值)
						$("input[name='id']").each(function(){
							var zv=$(this).val();
							if(selectAllNoCheckValue.indexOf(zv)==-1){//不再这里面
								$(this).prop("checked",true);
							}
						})
						$('input[name="id"]:checked').each(function(){
							$(this).parents('tr').css('background','#fafafa');
						})
						$('input[name="id"]:checked').each(function(){
							$(this).trigger("click");
							$(this).trigger("click");
							return false;
						})
					}
					
					var selectStatusVal=$("#geopgstate").val();//状态值
					if(''==selectStatusVal||undefined==selectStatusVal){
						//$('#table-quanxuan').css({"background-color":"#C1C1C1","cursor":"default"});
						$('#table-quanxuans').css({"visibility":"hidden"});
					}else{
						//$('#table-quanxuan').css({"background-color":"white","cursor":"pointer"});
						$('#table-quanxuans').css({"visibility":"visible"});
					}
					
					geoselect();
					$(".right .tbl .active").trigger("click");
				});
				return !1;
		});
	}
	function addLoginBtnEvent(){
		$(".btn3").bind("click",function(e){
			$("input[name=page]").val(0);
			/*if($("#first").val() == "true") {
				var action_ = $("form[name=fm]").attr("action");
				action_ = action_.replace("showVehicleBindJson","showFirstVehicleBindJson");
				$("form[name=fm]").attr("action",action_);
			} else {
				var action_ = $("form[name=fm]").attr("action");
				action_ = action_.replace("showFirstVehicleBindJson","showVehicleBindJson");
			}*/
			$("form[name=fm]").attr("action","showVehicleBindJson");
			$("form[name=fm]").submit();
			posMarker = undefined;
		});
		$(document).ready(function(){
			$(".btn3").click();
			if($("#first").val() == "true"){
				$("#first").val("false");
			}
		});
	}
	function setGeofenceInfoNoValide(){
		var centeraddress = $("#centeraddress").val();
		var centeraddress_old = $("#centeraddress_old").val();
		var latitude = $("#latitude").val();
		var longitude = $("#longitude").val();
		var radius = $("#radius").val();
		var radius_old = $("#radius_old").val();
		var geostatus_old = $("#geostatus_old").val();
		changeCheckedGeostat(longitude, latitude, radius);
		var chk_values =[];
		var geostatus_values =[];
		$('.check-dan').each(function(i, item){
			if($(item).is(':checked')) {
				chk_values.push($(this).val());
				geostatus_values.push($(".table2 tbody tr").eq(i).attr("geostat"));
			}
		});
		var data = {
			"id":chk_values,
			"address":centeraddress,
			"latitude":latitude,
			"longitude":longitude,
			"geostatus":geostatus_values,
			"radius":radius
		};
		$.ajax({url:f.locationPath+"/setGeofenceInfo?t="+new Date().getTime(), async:false, data:data });
	}
	f.setGeofenceInfoNoValide = setGeofenceInfoNoValide;
	function resetForm(){
		if(page){
			page.condition&&page.condition.keyword?$("input[name=keyword]").val(page.condition.keyword):!1;
			if(page.orders&&page.orders.length>0){
				$("input[name=orders\\[0\\]\\.property").val(page.orders[0].property);
				$("input[name=orders\\[0\\]\\.direction").val(page.orders[0].direction);
			}
		}
	}
	function registerSetPage(){
		f.Pages.registerPage(function(pageNow,pageConfig,p){
			resetForm();
			$("input[name=page]").val(pageNow);
			$("form[name=fm]").submit();
			posMarker = undefined;
		},"defaultPage");
	}
	function addOrderEvent(){
		var co = currentOrder;
		var coe = co?$("th[order="+co.property.replace(".",'\\.')+"]"):!1;
		if(co&&coe.length>0){
			coe.find("span.ico").eq(0).append("<span class='filter "+(co.direction=='DESC'?'':"current")+"'></span>");
		}
		$("th[order]").each(function(){
			$(this).css("cursor","pointer");
			$(this).click(function(){
				var property,direction='DESC';
				if(co&&co.property==$(this).attr("order")){
					direction = co.direction=='DESC'?'ASC':'DESC';
				}
				property = $(this).attr("order");
				currentOrder={property:property,direction:direction};
				resetForm();
				$("input[name=orders\\[0\\]\\.property").val(property);
				$("input[name=orders\\[0\\]\\.direction").val(direction);
				$("form[name=fm]").submit();
			});
		});
	}
	function addArrowEvent(){
		$(".arrow").click(function(){
			$(this).prev().toggle();alert('0');
			$(this).toggleClass('current');
			return !1;
		});
	}
	function _init(){
		_initMap();
		_initAutoComplete();
		addEnterEvent();
		addLoginBtnEvent();
		addArrowEvent();
	}
	_init();
	
	 
	function uniQueue(arrays){ 
		var arrs=[]; 
		var ms; 
		while(arrays.length>0){ 
			ms=arrays[0]; 
			arrs.push(ms); 
			arrays=$.grep(arrays,function(ns,is){ 
				return ns==ms; 
			},true); 
		} 
		return arrs; 
	} 
})(window.Fsp,jQuery,window);

猜你喜欢

转载自blog.csdn.net/wasd986523/article/details/71212139