基于js和openlayer计算2个经纬度点之间的距离
基于js和openlayer计算2个经纬度点之间的距离
//计算2个经纬度点之间的距离
//Haversine formula 算法
var harvensin=function()
{
this.earch_radius=6371008.8; // 地球半径 平均值 米
this.distance=function(lat1,lon1,lat2,lon2)
{
//用haversine公式计算球面两点间的距离。
//经纬度转换成弧度
var h_lat1=lat1*Math.PI/180.0;
var h_lon1=lon1*Math.PI/180.0;
var h_lat2=lat2*Math.PI/180.0;
var h_lon2=lon2*Math.PI/180.0;
//差值
var vlon=Math.abs(h_lon1-h_lon2);
var vlat=Math.abs(h_lat1-h_lat2);
//
var h=this.HaverSin(vlat)+Math.cos(h_lat1)*Math.cos(h_lat2)*this.HaverSin(vlon);
//
var d=2*this.earch_radius*Math.asin(Math.sqrt(h));
//
return d;
};
this.HaverSin=function(theta)
{
var v=Math.sin(theta/2);
return v*v;
};
};
//自定义函数 利用haversine算法公式
function latlongDistance(lat1,lon1,lat2,lon2)
{
var hs=new harvensin();
return hs.distance(lat1,lon1,lat2,lon2);
};
//latlongDistance(105.3,34.1,105.4,34.2)=11502.501545669946 (米)
//openlayer5.2 lib函数 长度计算调用方法
function sphereDistance(lat1,lon1,lat2,lon2)
{
var c1=[2];c1[0]=lon1;c1[1]=lat1;
var c2=[2];c2[0]=lon2;c2[1]=lat2;
return ol.sphere.getDistance(c1,c2);
};
//sphereDistance(105.3,34.1,105.4,34.2)=11502.501545669955 (米)
function getLength_custom()
{
var geo=drawLayer.getFirstGeometry();
var coordinates=geo.getCoordinates();
var len=0;
for(var i=0;i<coordinates.length-1;i++)
{
len+=latlongDistance(coordinates[i][1],coordinates[i][0],coordinates[i+1][1],coordinates[i+1][0]);
}
return len;
};
function getLength()
{
var geo=drawLayer.getFirstGeometry();
var options={};
options.projection=drawLayer.crs; //EPSG:4326
return ol.sphere.getLength(geo,options); //米
};
function getArea()
{
var geo=drawLayer.getFirstGeometry();
var options={};
options.projection=drawLayer.crs; //EPSG:4326
return ol.sphere.getArea(geo,options); //平方米
};
参考地址:
http://openlayers.org/en/latest/apidoc/
http://www.cnblogs.com/softfair/p/distance_of_two_latitude_and_longitude_points.html
转载自:https://blog.csdn.net/hsg77/article/details/85625048