sfl*_*che 13 javascript openlayers-3
使用OpenLayers 3,如何确定球形墨卡托(SRID:3857)投影中两点之间的距离?
我知道这distanceTo是在OpenLayers 2中使用的
point1.distanceTo(point2)
Run Code Online (Sandbox Code Playgroud)
我查看了OpenLayers 3文档,但我找不到类似的东西......
mar*_*v00 17
您可以使用Sphere对象计算两个坐标之间的距离,如下所示:
var distance = ol.sphere.WGS84.haversineDistance([0,0],[180,0]);
//20037508.34 meters
Run Code Online (Sandbox Code Playgroud)
Sphere还提供了各种算法来计算距离,如余弦,equirectangular等.您还可以创建半径为不同椭球的Sphere对象.
我不知道为什么文档不在线,但您可以检查球体对象源代码中可用的方法:https://github.com/openlayers/ol3/blob/master/src/ol/sphere. JS
我个人认为查看源代码是查找OpenLayers3答案的最佳方法;)
我正在使用一个相当简单的解决方案.我在两点之间实现了一个ol.geom.LineString对象并计算了该行的长度:
this.distanceBetweenPoints = function(latlng1, latlng2){
var line = new ol.geom.LineString([latlng1, latlng2]);
return Math.round(line.getLength() * 100) / 100;
};
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用一些格式化获取可读值:
this.formatDistance = function(length) {
if (length >= 1000) {
length = (Math.round(length / 1000 * 100) / 100) +
' ' + 'km';
} else {
length = Math.round(length) +
' ' + 'm';
}
return length;
}
Run Code Online (Sandbox Code Playgroud)
编辑:新的计算方法
实际上,您使用的投影距离可能是假的.我们在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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14469 次 |
| 最近记录: |