﻿// 地图网
// Ditu.net
// 调用Google地图服务的JavaScript
// JavaScript that interacts with Google Maps service
// 作者: 严勇敏
// Author: Yongmin Yan, Ph.D.
// 日期: 2006年9月27日
// Date: Sept. 27, 2006
// 版权声明:作者拥有此程序代码的版权,作者授权任何个人可以自由复制或修改此程序,但是使用者必须完全保留以上注释内容以尊重作者的版权
// This is copyrighted material. Modification or Redistribution of the code is permitted provided the above disclaimer is included without any modification
// 如果本程序对您有帮助,欢迎给原作者发邮件告知,地址: gistoday at gmail dot com。也希望您建立至地图网(ditu.net)的友情链接以示感谢
// If this script is helpful to you, the author would appreciate your notification by email, please contact gistoday at gmail dot com. A link back to ditu.net is also encouraged.
//

    //<![CDATA[
var G_map=null;
var LTMapWin=null;
var Photos=[];
var LastLat=0;
var LastLng=0;
var defLatDiff=0.00159;
var defLngDiff=0.00615;
var ScaleDiff=0;

    function G_load(Lat, Long) {
      if (GBrowserIsCompatible()) {
        G_map = new GMap2(document.getElementById("G_map"),{mapTypes:[G_HYBRID_MAP]});
	G_map.addControl(new GLargeMapControl());
	G_map.addControl(new GOverviewMapControl());
//	G_mapTypeControl = new GMapTypeControl();
//	G_map.addControl(G_mapTypeControl);
	if (arguments.length<2){lat=39.90153;long=116.39171;}
        G_map.setCenter(new GLatLng(Lat, Long), 17);
//	G_map.removeMapType(G_map.getCurrentMapType());
//	G_map.removeMapType(G_map.getCurrentMapType());
//	G_map.removeControl(G_mapTypeControl);
	GEvent.addListener(G_map,"moveend",G_MoveEnd);
	GEvent.addListener(G_map,"click",G_ClickEnd);
	G_MoveEnd();
      }
     else{
	document.getElementById("G_map").innerHTML="<p>您使用的网络浏览器无法显示地图。您需要以下任何一种网络浏览器：</p><p><ul><li>IE 6.0+</li><li>Firefox 1.0+</li><li>Safari 1.2.4+</li><li>Netscape 7.1+</li><li>Mozilla 1.4+</li><li>Opera 8.02+</li></ul></p>";
     }
    LTMapWin=top.LTMapsFrame;
		if (LTMapWin==null){
			if (document.getElementById("LT_maps")!=null){LTMapWin=window;}	
		}

		if (LTMapWin == null) {
			//alert('建议您打开首页网址http://www.ditu.net同时显示电子地图和卫星影像');
			document.getElementById("POIInfo").innerHTML="<font color=#FF0000>此卫星影像网页应与电子地图网页同时显示以达到最佳效果,点击正确的网站入口<a href=http://www.ditu.net>www.ditu.net</a>。</font>";
		}
    }


	function G_ZoomIn(){
		G_map.zoomIn();
	}

	function G_ZoomOut(){
		G_map.zoomOut();
	}

	function G_ZoomTo(zoomLevel){
		G_map.setZoom(zoomLevel);
	}

	function G_Recenter(lat,long,scale){
		if (G_map != null){
	        G_map.setCenter(new GLatLng(lat, long), scale);
		if (LTMapWin == null) {
			G_map.panTo(new GLatLng(lat-defLatDiff, long-defLngDiff));
		}
		else{
			var lngdiff=document.getElementById("LngDiff").value;
			if (lngdiff==""){lngdiff="0";}
			var latdiff=document.getElementById("LatDiff").value;
			if (latdiff==""){latdiff="0";}
			G_map.panTo(new GLatLng(lat - parseFloat(latdiff), long - parseFloat(lngdiff) ));
		}
		}
	}

	function G_Moveto(lat,long){
		if (G_map != null){
		if (LTMapWin == null) {
			G_map.panTo(new GLatLng(lat-defLatDiff, long-defLngDiff));
		}
		else{
			var lngdiff=document.getElementById("LngDiff").value;
			if (lngdiff==""){lngdiff="0";}
			var latdiff=document.getElementById("LatDiff").value;
			if (latdiff==""){latdiff="0";}
			G_map.panTo(new GLatLng(lat - parseFloat(latdiff), long - parseFloat(lngdiff) ));
		}
		}
	}

	function G_RecenterBounds(lat,long,ymin,xmin,ymax,xmax){
		var scale = G_map.getBoundsZoomLevel(new GLatLngBounds(new GLatLng(xmin,ymin), new GLatLng(xmax,ymax)));
		G_Recenter(lat,long,scale);
	}

	function G_Goto(lat,long,scale){
		if (G_map != null){
	        G_map.setCenter(new GLatLng(lat, long), scale);
		G_AddPOI(lat,long,'经度'+long+', 纬度'+lat,'实际经纬度');
		if (LTMapWin == null) {
		}
		else{
			var lngdiff=document.getElementById("LngDiff").value;
			if (lngdiff==""){lngdiff="0";}
			var latdiff=document.getElementById("LatDiff").value;
			if (latdiff==""){latdiff="0";}
			LTMapWin.LT_Recenter((lat + parseFloat(latdiff)) * 100000.0, (long + parseFloat(lngdiff)) * 100000.0, scale+ScaleDiff);
		}
		}
	}

	function G_GotoRealCoord(lat,long){
		G_map.panTo(new GLatLng(lat,long));		
		var controlmap = document.getElementById("MoveMap");		
		if ((LTMapWin != null) && (controlmap != null)) {		
			if (controlmap.checked){
			var lngdiff=document.getElementById("LngDiff").value;
			if (lngdiff==""){lngdiff="0";}
			var latdiff=document.getElementById("LatDiff").value;
			if (latdiff==""){latdiff="0";}
			LTMapWin.LT_Recenter((lat + parseFloat(latdiff)) * 100000.0, (long + parseFloat(lngdiff)) * 100000.0, parseInt(G_getScale())+ScaleDiff);
			}
		}
	}

	function G_MoveEnd(){
		var center = G_map.getCenter();
		var lng=document.getElementById("G_Lng");
		lng.value=center.lng();
		var lat=document.getElementById("G_Lat");
		lat.value=center.lat();
		var bounds=document.getElementById("G_Bounds");
		bounds.value=G_map.getBounds().toString();
		var scale=document.getElementById("G_Scale");
		scale.value=G_map.getZoom().toString();
		var bounds=G_map.getBounds();
		var minx=bounds.getSouthWest().lng();
		var miny=bounds.getSouthWest().lat();
		var maxx=bounds.getNorthEast().lng();
		var maxy=bounds.getNorthEast().lat();
		var xbuffer=(maxx-minx);
		var ybuffer=(maxy-miny);
		xbuffer=xbuffer>0.008?xbuffer:0.008;
		ybuffer=ybuffer>0.008?ybuffer:0.008;
		if ((Math.abs(center.lat()-LastLat) > ybuffer) || (Math.abs(center.lng()-LastLng) > xbuffer)) {
			G_LoadPhotos();
			LastLat=center.lat();
			LastLng=center.lng();
		}

	}

	function G_ClickEnd(overlay,point){
		if (point != null){
		var lng=document.getElementById("ClickLng");
		lng.value=point.lng()+'';
		var lat=document.getElementById("ClickLat");
		lat.value=point.lat()+'';

		if (overlay != null){}
		else if (document.ToolsForm && document.ToolsForm.Tools[1].checked){
			var poiinfo=document.getElementById("POIInfo");
			poiinfo.innerHTML="请填写兴趣点信息: 名称<input type='text' name='POITitle' id='POITitle' MaxLength=15 />(限15字)<br />具体描述<textarea name='POIDesc' id='POIDesc' rows='3' cols='30'></textarea>(限100字)";
			poiinfo.innerHTML=poiinfo.innerHTML+ "<input type=button name='AddPOI' id='AddPOI' value='提交兴趣点' onclick=\"Javascript:var ch=/\'/g;var title=document.getElementById('POITitle').value.replace(ch, '');var desc=document.getElementById('POIDesc').value.replace(ch, '');G_AddTempPOI(" + point.lat() + "," + point.lng() + ",title,desc);document.getElementById('POIInfo').innerHTML='改动位置，拽着它走走。如果想删除，请双击兴趣点。确认位置后请单击兴趣点预览效果(弹出信息窗口),并最终提交兴趣点。';\" />";
			poiinfo.innerHTML=poiinfo.innerHTML+"<p>名称和文字说明请勿使用单引号&#39;或双引号&quot;。填写完后请按提交兴趣点按钮,系统将生成一临时图标供您调整位置。确认位置后请再次点击兴趣点提交地图网保存。</p>";
		}
		}
	}

	function G_GetCenter(){
		var center = G_map.getCenter();
		return center.lng() + '' + center.lat();
	}
	
	function G_getCenterLng(){
		var lng=document.getElementById("G_Lng");
		return lng.value;		
	}

	function G_getCenterLat(){
		var lat=document.getElementById("G_Lat");
		return lat.value;		
	}

	function G_getScale(){
		var scale=document.getElementById("G_Scale");
		return scale.value;		
	}

	function CalculateDiff(){
		if (LTMapWin != null){
			var lngdiff = document.getElementById("LngDiff");
			lngdiff.value = parseFloat(LTMapWin.LT_getCenterLng())/100000.0 - parseFloat(G_getCenterLng());
			var latdiff = document.getElementById("LatDiff");
			latdiff.value = parseFloat(LTMapWin.LT_getCenterLat())/100000.0 - parseFloat(G_getCenterLat());
			var scalediff=document.getElementById("ScaleDiff");
			//scalediff.value = parseInt(LTMapWin.LT_getScale())+parseInt(G_getScale())-17;
			scalediff.value = parseInt(G_getScale())-parseInt(LTMapWin.LT_getScale());
			alert('系统将按目前电子地图和卫星影像的相对位置进行误差校正');
		}
	}

	function DefaultDiff(){
		if (LTMapWin != null){
			var lngdiff = document.getElementById("LngDiff");
			lngdiff.value = defLngDiff;
			var latdiff = document.getElementById("LatDiff");
			latdiff.value = defLatDiff;
			var scalediff = document.getElementById("ScaleDiff");
			scalediff.value = "0";
			alert('系统恢复使用确省误差校正参数(最适合北京地区)');
		}
	}

	function setLatLngDiff(LatDiff, LngDiff, ScaleDiff){
			var lngdiff = document.getElementById("LngDiff");
			lngdiff.value = LngDiff;
			var latdiff = document.getElementById("LatDiff");
			latdiff.value = LatDiff;
			if (arguments.length>2){
				var scalediff=document.getElementById("ScaleDiff");
				scalediff.value = ScaleDiff;
			}

	}

	function G_AddLTPOI(lat,long,title,desc){
		if (G_map != null){
		if (LTMapWin == null) {
			G_AddPOI(lat-defLatDiff, long-defLngDiff, title, desc);
		}
		else{
			var lngdiff=document.getElementById("LngDiff").value;
			if (lngdiff==""){lngdiff="0";}
			var latdiff=document.getElementById("LatDiff").value;
			if (latdiff==""){latdiff="0";}
			G_AddPOI(lat - parseFloat(latdiff), long - parseFloat(lngdiff), title, desc);
		}
		}
	}

	function G_AddPOI(lat,lng,title,desc){
		var marker = new GMarker(new GLatLng(lat,lng),{clickable:true});
		GEvent.addListener(marker,"mouseout",function(){G_map.closeInfoWindow();});
		GEvent.addListener(marker,"mouseover",function(){marker.openInfoWindowHtml('<strong>'+title+'</strong><br />'+desc,{maxWidth : 200});});
		//GEvent.addListener(marker,"click",function(){marker.openInfoWindowHtml("<a href='http://www.google.com/search?q="+title+"'>搜索互联网</a>",{maxWidth : 200});});
		GEvent.addListener(marker,"dblclick",function(){G_map.closeInfoWindow();var np=marker.getPoint();G_map.setCenter(np,17);});
		G_map.addOverlay(marker);
	}

	function G_AddTempPOI(lat,lng,title,desc){
		var marker = new GMarker(new GLatLng(lat,lng),{draggable:true,clickable:true});
		GEvent.addListener(marker,"dragstart",function(){G_map.closeInfoWindow();});
		//GEvent.addListener(marker,"mouseout",function(){G_map.closeInfoWindow();});
		//GEvent.addListener(marker,"dragend",function(){marker.openInfoWindowHtml(title + "(此功能正在测试,暂不保存兴趣点。)");});
		//GEvent.addListener(marker,"mouseover",function(){marker.openInfoWindowHtml(title + "。此功能正在测试,<br>暂不保存兴趣点。!<br />请单击兴趣点确认位置。<br />改动位置，拽着它走走.<br />如果想删除,请双击兴趣点.");});
		GEvent.addListener(marker,"click",function(){var np=marker.getPoint();marker.openInfoWindowHtml(desc + "<br /><a href=\"javascript:G_SubmitPOI(" + np.lat() + "," + np.lng() + ",'" + title + "','" + desc + "');G_map.closeInfoWindow();\">提交地图网保存兴趣点</a>" + "<br />",{maxWidth : 200});});
		//GEvent.addListener(marker,"click",function(){G_SubmitPOI('" + title + "','" + desc + "');G_map.closeInfoWindow();});
		GEvent.addListener(marker,"dblclick",function(){G_map.closeInfoWindow();G_map.removeOverlay(marker);});
		G_map.addOverlay(marker);
	}

	function G_ClearOverlays(){
		G_map.clearOverlays();
	}

	function G_AJAXCall(url, callbackFunction, respFormat) {
    		var httpObj = false;
    		if (typeof XMLHttpRequest != 'undefined') {
        		httpObj = new XMLHttpRequest();
    		} 
		else if (window.ActiveXObject) {
        		try{
            			httpObj = new ActiveXObject('Msxml2.XMLHTTP');
        		} 
			catch(e) {
            			try{
                			httpObj = new ActiveXObject('Microsoft.XMLHTTP');
            			} 
				catch(e) {}
        		}
    		}
    		if (!httpObj) {
			alert("浏览器不支持AJAX");
			return;
		}

    		httpObj.onreadystatechange = function() {
        		if (httpObj.readyState == 4) {
				if ((!(!respFormat)) && respFormat == 'XML'){
	            			callbackFunction(httpObj.responseXML);
				}
				else{
					callbackFunction(httpObj.responseText);
				}
				httpObj = undefined;
        		}
    		};
    		httpObj.open('GET', url, true);
    		httpObj.send(null);
	}

	function G_AfterSubmitPOI(respText){
		document.getElementById('POIInfo').innerHTML=respText;	
	}

	function G_SubmitPOI(lat,lng,title,desc){
		G_AJAXCall("/googlemaps/addPOI.asp?lat=" + lat + "&lng=" + lng + "&title=" + escape(title) + "&desc=" + escape(desc), G_AfterSubmitPOI);
	}
	
	function G_LoadKML(url){
		var bounds=G_map.getBounds();
		var kmlpath = url + "?BBOX=" + bounds.getSouthWest().lng() + "," + bounds.getSouthWest().lat() + "," + bounds.getNorthEast().lng() + "," + bounds.getNorthEast().lat();
		var kml = new GGeoXml(kmlpath);
		G_map.addOverlay(kml);
	}

	function G_LoadPhotos(){
		document.getElementById("ListInfoColumn").innerHTML = "正在查询照片...";
		var bounds=G_map.getBounds();
		var minx=bounds.getSouthWest().lng();
		var miny=bounds.getSouthWest().lat();
		var maxx=bounds.getNorthEast().lng();
		var maxy=bounds.getNorthEast().lat();
		var xbuffer=(maxx-minx)/2;
		var ybuffer=(maxy-miny)/2;
		xbuffer=xbuffer>0.004?xbuffer:0.004;
		ybuffer=ybuffer>0.004?ybuffer:0.004;
		minx=minx-xbuffer;
		maxx=maxx+xbuffer;
		miny=miny-ybuffer;
		maxy=maxy+ybuffer;
		var kmlpath = "/googlemaps/GetPhotosv2.asp" + "?BBOX=" + minx + "," + miny + "," + maxx + "," + maxy;
		G_AJAXCall(kmlpath, G_ProcessPhotos);
	}

	function G_ProcessPhotos(respText){
		if (respText.substring(0,12)=="<DituDotNet>"){
			var list = document.getElementById("ListInfoColumn");
			list.innerHTML = "实景照片服务暂时中断";
		}
		else{
		try{
			var xmlDoc;
			if (document.implementation && document.implementation.createDocument) { 
		    		var parser = new DOMParser(); 
				xmlDoc = parser.parseFromString(respText,"text/xml");
	  		}
			else{
				xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
				xmlDoc.async="false";
				xmlDoc.loadXML(respText);
			}
	                var placemarks = xmlDoc.documentElement.getElementsByTagName("Placemark");
			G_map.clearOverlays();
			Photos=[];
			var list = document.getElementById("ListInfoColumn");
			list.innerHTML="<p><center><strong>实景照片</strong></center></p>";
			if (placemarks.length==0){
				list.innerHTML = list.innerHTML + "<p>本地区尚无照片或者数据有误。您可以试着缩小地图或者改变区域再查一下。如果上次查询之后您移动了卫星影像，您可以点击<strong>照片</strong>链接重新查询照片。</p>";
			}
			else{
			list.innerHTML = list.innerHTML + "<ul>";
        	        for(var i = 0; i < placemarks.length; i++) {
                	    var point = placemarks[i].getElementsByTagName("Point")[0];
	                    var coords = point.getElementsByTagName("coordinates")[0].childNodes[0].nodeValue;
        	            coords = coords.split(",");
			    var name = "无题";
			    if (placemarks[i].getElementsByTagName("name")[0].hasChildNodes()){ 
                	    	name = placemarks[i].getElementsByTagName("name")[0].childNodes[0].nodeValue;
			    }
	                    var description = placemarks[i].getElementsByTagName("description")[0].childNodes[0].nodeValue;
			    Photos.push(description);
			    //list.innerHTML = list.innerHTML + "<p><a href=\"Javascript:G_map.panTo(new GLatLng(" + coords[1] + ", " + coords[0] + "));mywindow=window.open('', '_blank', 'width=600, height=400, toolbar=no, location=no, directories=no, scrollbars=yes, menubar=no, status=no, resizable=no');mywindow.document.write(Photos[" + i + "]); mywindow.document.close();\">" + name + "</a></p>";
			    list.innerHTML = list.innerHTML + "<li>" + (i+1) + ".<a href=\"Javascript:G_GotoRealCoord(" + coords[1] + ", " + coords[0] + ");mywindow=window.open('', '_blank', 'width=600, height=400, toolbar=no, location=no, directories=no, scrollbars=yes, menubar=no, status=no, resizable=no');mywindow.document.write(Photos[" + i + "]); mywindow.document.close();\">" + name + "</a></li>";
			    G_AddPhoto(parseFloat(coords[1]),parseFloat(coords[0]),name,description);
			}
			list.innerHTML = list.innerHTML + "</ul>";
			list.innerHTML = list.innerHTML + "<p>点击<a href='javascript:G_LoadPhotos();' title='查询本地区的照片'><strong>照片</strong></a>链接查询卫星影像所显示区域的实景照片。</p>";
			}
		}
			catch(e) {document.getElementById("ListInfoColumn").innerHTML = "数据有误,请改变区域再试一次";}
		}
	}

	function G_AddPhoto(lat,lng,name,description){
		var marker = new GMarker(new GLatLng(lat,lng),{clickable:true});
		GEvent.addListener(marker,"mouseout",function(){G_map.closeInfoWindow();});
		GEvent.addListener(marker,"mouseover",function(){marker.openInfoWindowHtml('<strong>'+name+'</strong><br />点击浏览照片',{maxWidth : 200});});
		GEvent.addListener(marker,"click",function(){G_GotoRealCoord(lat,lng);mywindow=window.open('', '_blank', 'width=600, height=400, toolbar=no, location=no, directories=no, scrollbars=yes, menubar=no, status=no, resizable=no');mywindow.document.write(description);mywindow.document.close();});
		G_map.addOverlay(marker);
	}

    //]]>

