﻿// JavaScript Document
function EarthDistance(_disUnit){
	this.EARTH_RADIUS = null;
	this.Pi = Math.PI;
	var tempDisUnit = _disUnit.replace(/^[ ]|[ ]$/g,"").toLowerCase();
	if(tempDisUnit == "km"){
		this.EARTH_RADIUS = 6378.137;
	}else if(tempDisUnit == "m"){
		this.EARTH_RADIUS = 6378137;
	}
	
	//求弧度
	this.Rad = function(_angle){
		return _angle * this.Pi / 180;
	};
	//求角度
	this.Ang = function(_rad){
		return _rad * 180 / this.Pi;
	};
	
	this.GetDistance = function(latA,lngA,latB,lngB){
		var angleAOB,tempDistance;
		angleAOB=Math.cos(this.Rad(lngA-lngB))*Math.cos(this.Rad(latA))*Math.cos(this.Rad(latB)) + Math.sin(this.Rad(latA))*Math.sin(this.Rad(latB));
		tempDistance = Math.acos(angleAOB)*this.EARTH_RADIUS;
		return tempDistance;
	};
	
	this.GetLatLngDif = function(lat,lng,_boundRadius){
		var difLatLng = new Array();
		var angleAOB;
		angleAOB = _boundRadius / this.EARTH_RADIUS;
		var lenAB,lenAO,lenBO;
		lenAO = lenBO = this.EARTH_RADIUS
		lenAB = Math.sqrt(Math.pow(lenAO,2) + Math.pow(lenBO,2) - 2*lenAO*lenBO*Math.cos(angleAOB));
		//I为A点纬度圈垂直于南北轴的交点,O为地心点
		var lenAI,lenBI,angAIB,angOAI;
		angOAI = lat;
		lenAI = Math.cos(this.Rad(angOAI))*this.EARTH_RADIUS;
		lenBI = lenAI;
		//lenAB^2 = lenAI^2 + lenBI^2 - 2*LenAI*lenBI*cos(angleAIB)
		angleAIB = Math.acos((Math.pow(lenAI,2) + Math.pow(lenBI,2) - Math.pow(lenAB,2)) / (2*lenAI*lenBI));
		var latDif = this.Ang(angleAIB);
		var lngDif = this.Ang(angleAOB);
		difLatLng.push(latDif);//East
		difLatLng.push(lngDif);//North
		return difLatLng;
	};
}