使用OpenLayers 3,如何确定球面墨卡托(SRID: 3857)投影中两点之间的距离?
我知道distanceTo被用于OpenLayers 2
point1.distanceTo(point2)我翻阅了OpenLayers 3 docs,但我没有发现任何类似的.
发布于 2014-10-28 16:44:04
您可以使用Sphere对象计算两个坐标之间的距离,如下所示:
var distance = ol.sphere.WGS84.haversineDistance([0,0],[180,0]);
//20037508.34 meters 球面还提供了各种计算距离的算法,如余弦、等长线等。你也可以用不同椭球的半径来创建球面物体。
我不知道为什么文档不在线,但是您可以检查球形对象的源代码:https://github.com/openlayers/ol3/blob/master/src/ol/sphere.js提供的方法。
我个人认为查看源代码是找到关于OpenLayers3的答案的最好方法;)
发布于 2015-02-11 12:27:55
我用的是一个相当简单的解决方案。我实例化了两个点之间的一个ol.geom.LineString对象,并计算了该行的长度:
this.distanceBetweenPoints = function(latlng1, latlng2){
var line = new ol.geom.LineString([latlng1, latlng2]);
return Math.round(line.getLength() * 100) / 100;
};然后,您可以使用一些格式化方法获得一个可读的值:
this.formatDistance = function(length) {
if (length >= 1000) {
length = (Math.round(length / 1000 * 100) / 100) +
' ' + 'km';
} else {
length = Math.round(length) +
' ' + 'm';
}
return length;
}编辑:计算的新方法
实际上,对于您使用的投影,距离可能是假的。我们在OL3的github上对此进行了相当长的讨论,您可以在那里看到它:https://github.com/openlayers/ol3/issues/3533
总之,您需要使用该函数才能得到精确的计算结果:
/**
* format length output
* @param {ol.geom.LineString} line
* @return {string}
*/
export default function mapFormatLength(projection, line) {
var length;
var coordinates = line.getCoordinates();
length = 0;
for (var i = 0, ii = coordinates.length - 1; i < ii; ++i) {
var c1 = ol.proj.transform(coordinates[i], projection, 'EPSG:4326');
var c2 = ol.proj.transform(coordinates[i + 1], projection, 'EPSG:4326');
length += mapConst.wgs84Sphere.haversineDistance(c1, c2);
}
var output;
if (length > 1000) {
output = (Math.round(length / 1000 * 100) / 100) +
' ' + 'km';
} else {
output = (Math.round(length * 100) / 100) +
' ' + 'm';
}
return output;
}发布于 2015-05-16 10:30:47
只是想再增加一个选项。这不是ol3依赖的。
function toRad(x) {return x * Math.PI / 180;}
function SphericalCosinus(lat1, lon1, lat2, lon2) {
var R = 6371; // km
var dLon = toRad(lon2 - lon1),
lat1 = toRad(lat1),
lat2 = toRad(lat2),
d = Math.acos(Math.sin(lat1)*Math.sin(lat2) + Math.cos(lat1)*Math.cos(lat2) * Math.cos(dLon)) * R;
return d;
}https://stackoverflow.com/questions/26071490
复制相似问题