var polyline;
var polylinesArray = new Array();
//距离标记数组
var lenArray = new Array();
var DistanceClickListener = null;
var Bdistance=null;


//距离
function openDistance() {
		hidetoolPanel();
		//closeRectangShape();
		closeDistance();
		if(mapType==2){
        	//清除上次记录
			closeDistanceButton.deletebutton();
			closeRectangShape();
			DistanceClickListener = google.maps.event.addListener(map, "click",
			function(event) {
				addMarker(event.latLng);
			});
		}else if(mapType==3){
			ruler1.turnOn();
		}else{
			//添加测距
			Bdistance =new BMapLib.DistanceTool(baidMap);
			
			Bdistance.open();
		}
}

function closeDistance(){
		distancelength=0;
		deleteOverlays();
		try{
		google.maps.event.removeListener(DistanceClickListener);
		}catch(e){}
		if(endMarker!=null){
			//endMarker.setMap(null);
			endMarker=null;
		}
		
		if(closeDistanceButton.closebutton!=null){
			//closeDistanceButton.closebutton.setMap(null);
		}
		
		if(Bdistance!=null){
			Bdistance.close();
		}
}


var closeDistanceButton={
	 closebutton : null,
	 closebuttonevent : null,
	 addbutton : function(Latlng_){
	 	var image = {
					    url: Url.distanceclose,
					    size: new google.maps.Size(12, 12),
					    origin: new google.maps.Point(0,0),//位置
					    anchor: new google.maps.Point(0, 3)
					  };
		
		this.closebutton=new google.maps.Marker({
							      position: Latlng_,
							      map: map,
							      icon: image
							});
		this.closebuttonevent=google.maps.event.addListener(this.closebutton, "click", function (e) {
					      closeDistance();
					      closeDistanceButton.deletebutton();
					 });
	 },
	 deletebutton : function(){
	 	if(this.closebuttonevent!=null&&this.closebutton!=null){
		 	google.maps.event.removeListener(this.closebuttonevent);
		 	this.closebutton.setMap(null);
		 	this.closebutton=null;
	 	}
	 }
	 
};
var endMarker=null;
var distancelength=0;
//添加新标记
function addMarker(location) {
	if (lenArray.length == 0) {
		var icon = Url.distancestart;
	} else {
		if (lenArray.length >= 2) {
			marker.setMap(null);
			if(endMarker!=null){
				//endMarker.setMap(null);
				endMarker=null;
			}
		}
		var icon = Url.distanceend;
	}
	//标记选项
	var myOptions = {
		position: location,
		draggable: true,
		map: map,
		icon: icon
	};
	marker = new google.maps.Marker(myOptions);
	//双击
	google.maps.event.addListener(marker, 'click',
	function() {
		//放入marker
		lenArray.push(marker);
		drawOverlay();
	});
	//拖动结束事件
	google.maps.event.addListener(marker, 'dragend',
	function() {
		lenArray.push(marker);
		drawOverlay();
		endMarker = new myLableMarker(map,"<div class=\"iconTheStyle\" style=\"background:#f5fcb8;  font-size:12px; color:#000000; font-weight:bold; white-space:nowrap; border:1px solid #666666;\" ><span id=\"closeDistance\">"+language.zjl+": " +distancelength+" km</span></div>",marker.getPosition());
		//endMarker.setMap(map);
		closeDistanceButton.addbutton(marker.getPosition());
	});
	
	//拖动结束事件
	google.maps.event.addListener(marker, 'dragstart',
	function() {
		lenArray.push(marker);
		drawOverlay();
		if(endMarker!=null){
			//endMarker.setMap(null);
			endMarker=null;
		}
		closeDistanceButton.deletebutton();
	});
		
	lenArray.push(marker);
	drawOverlay();
	if(lenArray.length >= 2){
		endMarker = new myLableMarker(map,"<div id=\"distancelength\" class=\"iconTheStyle\" style=\"background:#f5fcb8;  font-size:12px; color:#000000; font-weight:bold; white-space:nowrap; border:1px solid #666666;\">"+language.zjl+": " +distancelength+" km</div>",location);
		//endMarker.setMap(map);
		closeDistanceButton.deletebutton();
		closeDistanceButton.addbutton(location);
	}
}

//画出路径覆盖层
function drawOverlay() {
	//路线数组
	var flightPlanCoordinates = [];
	//
	//将坐标压入路线数组
	if (lenArray) {
		for (var i=0;i<lenArray.length;i++) {
			flightPlanCoordinates.push(lenArray[i].getPosition());
		}
	}
	//路径选项
	var myOptions = {
		path: flightPlanCoordinates,
		map: map,
		strokeColor: "#FF0000",
		strokeOpacity: 1.0,
		strokeWeight: 2
	};
	polyline = new google.maps.Polyline(myOptions);
	//清除原有折线路径
	if (polylinesArray) {
		for (var i=0 ; i<polylinesArray.length;i++) {
			polylinesArray[i].setMap(null);
		}
		polylinesArray = [];
	}
	polyline.setMap(map);
	distancelength= (polyline.getLength() / 1000).toFixed(3);
	polylinesArray.push(polyline);
}

try{

		///距离算法
		google.maps.LatLng.prototype.distanceFrom = function(latlng) {
			var lat = [this.lat(), latlng.lat()]
			var lng = [this.lng(), latlng.lng()] //var R = 6371; // km (change this constant to get miles)
			var R = 6378137; // In meters
			var dLat = (lat[1] - lat[0]) * Math.PI / 180;
			var dLng = (lng[1] - lng[0]) * Math.PI / 180;
			var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat[0] * Math.PI / 180) * Math.cos(lat[1] * Math.PI / 180) * Math.sin(dLng / 2) * Math.sin(dLng / 2);
			var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
			var d = R * c;
			return Math.round(d);
		}
		// //
		google.maps.Marker.prototype.distanceFrom = function(marker) {
			return this.getPosition().distanceFrom(marker.getPosition());
		}
		// //
		google.maps.Polyline.prototype.getLength = function() {
			var d = 0;
			var path = this.getPath();
			var latlng;
			for (var i = 0; i < path.getLength() - 1; i++) {
				latlng = [path.getAt(i), path.getAt(i + 1)];
				d += latlng[0].distanceFrom(latlng[1]);
			}
			return d;
		}
}catch(e){

}

// 删除所有叠加物 
function deleteOverlays() {
	if (lenArray) {
		for (var i=0;i<lenArray.length;i++) {
			lenArray[i].setMap(null);
		}
		lenArray.length = 0;
	}

	//清除原有折线路径
	if (polylinesArray) {
		for (var i=0 ; i<polylinesArray.length;i++) {
			polylinesArray[i].setMap(null);
		}
		polylinesArray = [];
	}
}

function myLableMarker(map, text, latLng,_id){
		 this.map_ = map;
		 this.text_ = text;
		 this.latLng_ = latLng;
		 this.div_ = null;
		 this.id = _id || "";
		 this.setMap(map);
}
// 继承自  google.maps.OverlayView
try{
	myLableMarker.prototype = new google.maps.OverlayView();
}catch(e){}
// 当准备将 悬浮层 添加到地图上时 调用
myLableMarker.prototype.onAdd = function(){
	 var div = document.createElement('DIV');
	 div.style.border = 'none';
	 div.style.position='absolute';   
	 div.innerHTML = this.text_;
	 this.div_ = div;	    
	 var panes = this.getPanes();
	 panes.overlayLayer.appendChild(div);
};
  
// 当第一次在地图上显示时 调用
myLableMarker.prototype.draw = function(){
	 var overlayProjection = this.getProjection();
	 var latLng = overlayProjection.fromLatLngToDivPixel(this.latLng_);
	 // 设置层的大小 和 位置
	 var div = this.div_;
	 var size = new google.maps.Size(17, -10); // 修正坐标的值;Size(width:number, height:number, widthUnit?:string, heightUnit?:string)
	 div.style.left = (latLng.x + size.width) + 'px';
	 div.style.top = (latLng.y + size.height) + 'px';
	 div.style.zIndex=9999;
};
// 当设置 悬浮层的 setMap(null) 会自动调用 
myLableMarker.prototype.onRemove = function(){
	 this.div_.parentNode.removeChild(this.div_);
	 this.div_ = null;
};