www.pudn.com > GoogleEarth-information-systems.rar > func.php, change:2012-06-22,size:16703b


 
 
//产生唯一值 
function getUniqueId(){ 
    return "oid"+(new Date()).getTime()+ parseInt(Math.random()*100000); 
} 
 
function JWAarrToJson(arr) { 
	var Json = '['; 
	if(arr.length > 0){ 
		for(var i = 0; i < arr.length; i++){ 
			if(i > 0){ 
				Json += ","; 
			} 
			Json += "{lat:'" + arr[i][0] + "',lng:'" + arr[i][1] + "',alt:'" + arr[i][2] + "'}"; 
		} 
	} 
	Json += "]"; 
	return Json; 
} 
 
function getObjectById(id) { 
	var foundObject = null;  
	// Traverse the DOM, looking for the object with the given ID.  
	gex.dom.walk({  
		rootObject: ge,  
		visitCallback: function() {  
		    if ('getId' in this && this.getId() == id) {  
			    foundObject = this;  
			    return false;  // Stop the walk.  
		    }  
		}  
	});  
	return foundObject;  
} 
 
 
 
function pad2(s) { 
	return ((s.length < 2) ? '0' : '') + s;  
} 
//合并颜色和透明度 
function mergeColorOpacity(color, opacity) { 
	color = color ? gex.util.parseColor(color) : 'ffffffff'; 
	if (!geo.util.isUndefined(opacity)) {  
		color = pad2(Math.floor(255 * opacity).toString(16)) + color.substring(2); 
	}  
	return color;  
} 
//绘制id属性的点 
function drawPoint(id, point, name, description){ 
    gex.dom.addPlacemark({id: id, name: name, point: point, description: description, style: pointStyle});  //stockIcon: 'paddle/pink-diamond' 
} 
//绘制带id属性的点 
function drawPointId(lat, lng, name, description, id){ 
    gex.dom.addPlacemark({id: id, name: name, point: [lat, lng], description: description}); 
} 
//绘制路径前端点 
function drawPathCap(id, point, name, description){ 
    //gex.dom.addLineStringPlacemark({id: id, name: name, point: point, lineString: [point], description: description, style: pathStyle}); 
    gex.dom.addLineStringPlacemark({id: id, name: ' ', point: point, lineString: [point], description: description, style: pathStyle}); 
} 
//添加路径 
function addPathPoint(id, point){ 
    getObjectById(id).getGeometry().getGeometries().getChildNodes().item(1).getCoordinates().pushLatLngAlt(point[0], point[1], point[2]); 
	 //drawPathRearCap(id); 
} 
//绘制路径后端点 
function drawPathRearCap(id){ 
	var geometriesObj = getObjectById(id).getGeometry().getGeometries(); 
    var coordinates = geometriesObj.getChildNodes().item(1).getCoordinates(); 
	var pointLength = coordinates.getLength(); 
    geometriesObj.appendChild(gex.dom.buildPoint(coordinates.get(pointLength-1))); 
} 
     //绘制线 
function drawPath(id, points, name, description){ 
    gex.dom.addLineStringPlacemark({id: id, name: name, lineString: points, description: description, style: pathStyle}); 
} 
//绘制矩形 
function drawRectangle(id, points, name, description){ 
	//alert(id); 
    gex.dom.addPolygonPlacemark(points, {id: id, name: name, description: description, style: { poly: { color: 'White', opacity: 0.3, fill: true, outline: true }, line: pathStyle }}); 
} 
function drawPolygonCap(id, points, name, description){ 
    gex.dom.addPolygonPlacemark(points, {id: id, name: name, description: description, style: { poly: { color: 'White', opacity: 0.3, fill: true, outline: true }, line: pathStyle }}); 
} 
//添加多边形顶点 
function addPolygonPoint(id, point){ 
	//alert(id); 
    //getObjectById(id).getGeometry().getCoordinates().pushLatLngAlt(point[0], point[1], point[2]); 
    getObjectById(id).getGeometry().getOuterBoundary().getCoordinates().pushLatLngAlt(point[0], point[1], point[2]);  
 
} 
//绘制多边形(圆、扇形) 
function drawPolygon(id, points, name, description){ 
    gex.dom.addPolygonPlacemark(points, {id: id, name: name, description: description, style: { poly: { color: 'White', opacity: 0.3, fill: true, outline: true }, line: pathStyle }}); 
} 
//创建geoPoint对象 
function createGeoPointByLatLngAlt(lat, lng, alt){ 
    return new geo.Point(lat, lng, alt); 
} 
 
//获取geoPoint对象的高程 
function getGeoPointAltitude(point){ 
    return ge.getGlobe().getGroundAltitude(point.lat(), point.lng()).toFixed(2);   //单位:米(m) 
} 
 
//计算两点之间水平距离 
function getHorizontalDistance(startPoint, endPoint){ 
	//英制长度单位: 1码(yard)=0.9144米,1迈(mile)=1609.344 米 = 1760 码 
    return startPoint.distance(endPoint).mul(getStarRadius(lastMapMod));   //单位:米(m) 
} 
 
//计算两点之间高程差(垂直距离) 
function getVerticalDistance(startPoint, endPoint){ 
    return abS(startPoint.altitude() - endPoint.altitude()).toFixed(2);   //单位:米(m) 
} 
 
//计算两点之间实际距离,加入高程数据 
function getActualDistance(startPoint, endPoint){ 
	//根据勾股定理 
	return sqRt(sqIt(getHorizontalDistance(startPoint, endPoint)) + sqIt(getVerticalDistance(startPoint, endPoint))).toFixed(2);   //单位:米(m) 
} 
 
//按距离和角度定位地标位置 
//getPointLocationByDistanceandHeading,返回geoPoint对象 
function getPointLocationByDH(startPoint, endPoint, d){ 
    return geo.math.destination(startPoint, {distance: parseFloat(d).div(getStarRadius(lastMapMod)), heading: startPoint.heading(endPoint)}); 
} 
 
function getPointLocationByDHA(startPoint, d, angle){ 
    return geo.math.destination(startPoint, {distance: parseFloat(d).div(getStarRadius(lastMapMod)), heading: angle}); 
} 
 
//平移地图 
function moveMapToPoint(destPoint, range, speed){ 
	if(speed==6){ 
	    speed = ge.SPEED_TELEPORT; 
	} 
	var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND); 
	lookAt.setLatitude(destPoint.lat());  //设置纬度 
	lookAt.setLongitude(destPoint.lng());   //设置经度 
	//lookAt.setHeading(0);  //方位角度 
    lookAt.setTilt(0);  //倾斜度 
	lookAt.setRange(range);  //放大程度 
	ge.getOptions().setFlyToSpeed(speed);  //设置地图移动速度 
	ge.getView().setAbstractView(lookAt); 
	/* 
	//ge.getOptions().setFlyToSpeed(ge.SPEED_TELEPORT);  //设置地图移动速度 
	var camera = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE_TO_GROUND); 
	camera.setLatitude(destPoint.lat());  //设置纬度 
	camera.setLongitude(destPoint.lng());   //设置经度 
	camera.setHeading(0);  //方位角度 
	camera.setTilt(0);  
	camera.setAltitude(range); 
	ge.getOptions().setFlyToSpeed(speed); 
	ge.getView().setAbstractView(camera); 
*/ 
} 
 
function rotateMap(angle){ 
	var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND); 
	lookAt.setHeading(angle);  //方位角度 
	ge.getView().setAbstractView(lookAt); 
} 
 
//暂停执行num为暂停毫秒数 
function sleep(num)   //JK  
{  
	var tempDate = new Date();  
	var goneMsel = 0;  
	while(goneMsel < num)  
	{  
		goneMsel = new Date() - tempDate;  
	}  
	return true;  
}  
 
//获得当前目录路径 
function getCurrentDirectory(){ 
	var locHref = location.href; 
	var locArray = locHref.split("/"); 
    /**这里测试locArray效果** 
    for(x in locArray){ 
      document.write("locArray["); 
      document.write(x+"]: "); 
      document.write(locArray[x]+"<br />"); 
    } 
    **/ 
    delete locArray[locArray.length-1]; 
    var dirTxt = locArray.join("/"); 
    return dirTxt; 
} 
 
//根据两点计算直角三角形直角点 
function getTrianglePoint(firstPoint, lastPoint){ 
	var c = getHorizontalDistance(firstPoint, lastPoint); 
    var angle1 = firstPoint.heading(new geo.Point(firstPoint.lat(), lastPoint.lng())); 
	var angle2 = firstPoint.heading(lastPoint); 
	var angle = Math.abs(angle1.sub(angle2)); 
	//alert(angle1+","+angle2+","+angle); 
	var a = c.mul(Math.cos(angle.mul(Math.PI).div(180))); 
	//var b = 10*Math.sin(30); 
	//var b = c.mul(Math.sin(angle)); 
	//alert(Math.sin(30*Math.PI/180)); 
	return getPointLocationByDHA(firstPoint, a, angle1); 
} 
 
//根据一点计算矩形的另外三个顶点 
function getRectanglePoints(firstpoint, d, p){ 
	//d = parseFloat(d).mul(getStarRadius(lastMapMod)); 
	pPoints[0] = firstpoint; 
	pPoints[1] = getPointLocationByDHA(pPoints[0], d*p, hheading); 
	pPoints[2] = getPointLocationByDHA(pPoints[1], 2*d*(p-1), vheading); 
	pPoints[3] = getPointLocationByDHA(pPoints[0], 2*d*(p-1), vheading); 
} 
 
//搜索位置 
function searchLocation(lat, lng){ 
	//alert(lat+","+lng); 
	var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND); 
	lookAt.setLatitude(parseFloat(lat));  //设置纬度 
	lookAt.setLongitude(parseFloat(lng));   //设置经度 
	//lookAt.setHeading(0);  //方位角度 
   // lookAt.setTilt(0);  //倾斜度 
	lookAt.setRange(10000);  //放大程度 
	ge.getOptions().setFlyToSpeed(2);  //设置地图移动速度 
	ge.getView().setAbstractView(lookAt); 
	//sleep(1000); 
    drawPointId(lat, lng, "目标点", "经度:"+lat+",纬度:"+lng, getUniqueId()); 
} 
 
//计算路线距离 
function computePathDistance(obj){ 
	//var obj = getObjectById(objectId); 
	var d = 0; 
	var coordinates = []; 
	var length = 0; 
	if('getType' in obj.getGeometry() && obj.getGeometry().getType() == 'KmlLineString'){ 
		coordinates = obj.getGeometry().getCoordinates();  
		length = coordinates.getLength(); 
		if(length > 1){ 
			for (var i = 1; i < length; i++ ){ 
				d = parseFloat(d).add(parseFloat(getHorizontalDistance(new geo.Point(coordinates.get(i-1)), new geo.Point(coordinates.get(i))).toFixed(2))); 
			} 
		} 
		//alert('KmlLineString'); 
	}else if('getType' in obj.getGeometry() && obj.getGeometry().getType() == 'KmlMultiGeometry'){ 
		if(obj.getGeometry().getGeometries().getChildNodes().item(1).getType() == 'KmlLineString'){ 
			coordinates = obj.getGeometry().getGeometries().getChildNodes().item(1).getCoordinates(); 
			length = coordinates.getLength(); 
			//alert(coordLength); 
			if(length > 1){ 
				for (var i = 1; i < length; i++ ){ 
					d = parseFloat(d).add(parseFloat(getHorizontalDistance(new geo.Point(coordinates.get(i-1)), new geo.Point(coordinates.get(i))).toFixed(2))); 
				} 
			} 
		} 
		//alert('KmlMultiGeometry');get(pointLength-1).getLatitude() 
	}else{ 
		//alert('dddddddddddd'); 
	} 
	return d; 
} 
 
function getStarRadius(star){ 
    var r = 6371000; //m,地球半径 
	var rMoon = 1737400; 
	var rMars = 3397200; 
	var ratio = 1; 
    if(star == 'moon'){ 
        ratio = rMoon.div(r); 
	}else if(star == 'mars'){ 
        ratio = rMars.div(r); 
	}else{ 
 
	} 
	return ratio; 
} 
 
//测面积和周长 
function computeAreaAndC(obj){ 
	var params = [0, 0]; 
	switch(obj.getGeometry().getType()){ 
		case 'KmlLinearRing': 
		case 'KmlPolygon':  //测面积和周长 
		    var coords = obj.getGeometry().getOuterBoundary().getCoordinates(); 
			if(coords.getLength() >= 3){ 
                params = getPolygonAreaAndC(coords); 
			} 
            break; 
		default: 
	} 
	return params; 
} 
 
//计算多边形面积和周长 
function getPolygonAreaAndC(geoPoints){ 
	//alert(geoPoints.getLength()); 
	//alert(Math.sin((360+30)*Math.PI/180)); 
	var params = [0, 0]; 
	var length = geoPoints.getLength(); 
	var firstGeoPoint = new geo.Point(geoPoints.get(0)); 
	var lastGeoPoint = new geo.Point(geoPoints.get(length-1)); 
	var geoPointi = null; 
    var geoPointii = null; 
	var angle1 = 0; 
	var angle2 = firstGeoPoint.heading(lastGeoPoint); 
	var angle = 0; 
	var d = 0; 
	var c = 0; 
	var x = []; 
	var y = []; 
	x.push(0); 
	y.push(0); 
    for(var i = 1; i < length; i++){ 
		geoPointi = new geo.Point(geoPoints.get(i-1)); 
		geoPointii = new geo.Point(geoPoints.get(i)); 
		d = getHorizontalDistance(geoPointi, geoPointii);  //一条边长 
		c = getHorizontalDistance(firstGeoPoint, geoPointii);  //改点到起点长度 
        params[0] = parseFloat(params[0]).add(parseFloat(d)); 
        angle1 = firstGeoPoint.heading(geoPointii); 
	    angle = angle2.sub(angle1).add(360); 
		x.push(Math.cos(angle.mul(Math.PI).div(180)).mul(c)); 
		y.push(Math.sin(angle.mul(Math.PI).div(180)).mul(c)); 
	} 
    params[0] = parseFloat(params[0]).add(parseFloat(getHorizontalDistance(new geo.Point(geoPoints.get(0)), new geo.Point(geoPoints.get(length-1))))); 
    params[1] = getPolygonAreaByCoords(x, y); 
	//alert(params[0]); 
	return params; 
} 
 
function getPolygonAreaByCoords(x, y){ 
    //alert(coords); 
	var s = 0; 
	var n = x.length; 
	x[n] = x[0]; 
	y[n] = y[0]; 
	for(var i = 0; i < n-1; i++){ 
        s = s.add(x[i].mul(y[i+1]).sub(x[i+1].mul(y[i]))); 
	} 
	if(n > 1){ 
        s = s.add(x[n].mul(y[0]).sub(x[0].mul(y[n]))); 
	} 
	s = Math.abs(s).mul(0.5); 
	return s; 
} 
 
var pageStopRunFlag = false; 
function cancelWebbrowserRun(key){ 
    //alert("aaaaaaaaaaaaaaa"); 
	if(key == "stop"){ 
        pageStopRunFlag = true; 
	}else{ 
        pageStopRunFlag = false; 
	} 
} 
 
//导入kml文件 
function importKmlFile(kmlString){ 
	var flag = 0; 
	//alert(filename); 
	//filename = 'http://localhost/GETest/Kmls/乌鲁木齐点、路径、多边形.kml'; 
    //var href = 'http://code.google.com/apis/earth/documentation/samples/kml_example.kml'; 
	var kmlObject = ge.parseKml(kmlString);  
	if(kmlObject){ 
	    ge.getFeatures().appendChild(kmlObject); 
        if (kmlObject.getAbstractView()){ 
			ge.getView().setAbstractView(kmlObject.getAbstractView()); 
		}else{ 
            moveMapToPoint(getFirstKmlObject(kmlString), 10000, 2); 
		} 
		flag = 1; 
	} 
	return flag; 
} 
 
function getFirstKmlObject(kmlString){ 
	var xmlDoc2 = new ActiveXObject('Microsoft.XMLDOM'); 
	xmlDoc2.async = 'false'; 
	xmlDoc2.loadXML(kmlString); 
	var DocRoot = xmlDoc2.documentElement; 
	var coords = DocRoot.selectSingleNode('//coordinates').text.Trim().split(' '); 
	var coord = coords[0].split(','); 
	//alert(coord); 
	return new geo.Point(parseFloat(coord[1]), parseFloat(coord[0]), parseFloat(coord[2])); 
} 
 
//获取地标KML字符串 
function getGEKml(){ 
	var output = ''; 
	var kmlString = '<?xml version="1.0" encoding="UTF-8"?>\r\n<kml xmlns="http://www.opengis.net/kml/2.2"' 
	               +'xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2"' 
				   +'xmlns:atom="http://www.w3.org/2005/Atom">\r\n<Document>\r\n'; 
	var nodes = ge.getFeatures().getChildNodes(); 
	var nodesCount = nodes.getLength(); 
	try 
	{ 
		var xmlDoc2 = new ActiveXObject('Microsoft.XMLDOM'); 
        xmlDoc2.async = 'false'; 
		var DocRoot = null; 
		for(var i = 0; i < nodesCount; i++){ 
			xmlDoc2.loadXML(nodes.item(i).getKml()); 
			DocRoot = xmlDoc2.documentElement; 
			if(!DocRoot.selectSingleNode('//Document')){ 
   			    kmlString += (DocRoot.selectSingleNode('//Placemark').xml + '\r\n').replace('xmlns="http://www.opengis.net/kml/2.2" ', '');  
			}else{ 
				var docNodes = DocRoot.selectNodes('//Document/*'); 
				var docNodesCount = docNodes.length; 
				for(var j = 0; j < docNodesCount; j++){ 
                    kmlString += (docNodes[j].xml + '\r\n').replace('xmlns="http://www.opengis.net/kml/2.2" ', ''); 
                   // alert(docNodes[j].xml); 
				} 
			} 
		} 
		kmlString += '</Document>\r\n</kml>'; 
		kmlString = formatKmlForHtml(kmlString); 
	} 
	catch (err){ 
	    alert('error'); 
	} 
    return kmlString; 
} 
 
//格式化提取的kml字符串 
function formatKmlForHtml(output) { 
   output = output.replace(/</g, '&lt;').replace(/>/g, '&gt;'); 
   output = output.replace(/\t/g, '  '); 
   output = output.replace(/\" xmlns/g, '\"\n     xmlns'); 
   return output; 
} 
 
function returnPointJson(point){ 
    return '{lat:"'+ point.lat().toFixed(6) +'",lng:"'+ point.lng().toFixed(6) +'",alt:"'+ ge.getGlobe().getGroundAltitude(point.lat(), point.lng()).toFixed(2) +'"},'; 
} 
 
//根据地址搜索位置 
function searchLatLngByLocation(a){ 
	//alert(a); 
	$.getJSON( 
	   'http://maps.googleapis.com/maps/api/geocode/json?address='+a+'&sensor=false', 
	 // { address: a, sensor: 'false' }, 
	   function(json){ 
		   if(json['status'] == 'OK'){ 
			  //alert('aaaa'); 
			  var lat = json['results'][0]['geometry']['location']['lat']; 
		      var lng = json['results'][0]['geometry']['location']['lng']; 
			  searchLocation(lat, lng); 
		   } 
	  }); 
} 
 
//根据经纬度返回高精度海拔数据(单点) 
function getSinglePointAltitude(point){ 
	$.getJSON( 
	   'http://maps.googleapis.com/maps/api/elevation/json?locations='+point.value.lat()+','+point.value.lng()+'&sensor=false', 
	   function(json){ 
		   if(json['status'] == 'OK'){ 
		       data += '{name:"' + point.key + '",lat:"'+point.value.lat().toFixed(6)+'",lng:"'+point.value.lng().toFixed(6)+'",alt:"'+json['results'][0]['elevation'].toFixed(2)+'"},'; 
		   }else{ 
               data += '{name:"' + point.key + '",lat:"' + point.value.lat().toFixed(6) +'",lng:"'+ point.value.lng().toFixed(6) +'",alt:"空"},'; 
		   } 
		   alert(json['results'][0]['elevation'].toFixed(2)); 
		   //extractPointsElevationsHighQuick(); 
    }); 
}