首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >OpenLayers 3:如何计算两点之间的距离?

OpenLayers 3:如何计算两点之间的距离?
EN

Stack Overflow用户
提问于 2014-09-27 05:04:51
回答 5查看 19.3K关注 0票数 14

使用OpenLayers 3,如何确定球面墨卡托(SRID: 3857)投影中两点之间的距离?

我知道distanceTo被用于OpenLayers 2

代码语言:javascript
复制
point1.distanceTo(point2)

我翻阅了OpenLayers 3 docs,但我没有发现任何类似的.

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2014-10-28 16:44:04

您可以使用Sphere对象计算两个坐标之间的距离,如下所示:

代码语言:javascript
复制
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的答案的最好方法;)

票数 19
EN

Stack Overflow用户

发布于 2015-02-11 12:27:55

我用的是一个相当简单的解决方案。我实例化了两个点之间的一个ol.geom.LineString对象,并计算了该行的长度:

代码语言:javascript
复制
        this.distanceBetweenPoints = function(latlng1, latlng2){
            var line = new ol.geom.LineString([latlng1, latlng2]);
            return Math.round(line.getLength() * 100) / 100;
        };

然后,您可以使用一些格式化方法获得一个可读的值:

代码语言:javascript
复制
        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

总之,您需要使用该函数才能得到精确的计算结果:

代码语言:javascript
复制
/**
 * 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;
}
票数 5
EN

Stack Overflow用户

发布于 2015-05-16 10:30:47

只是想再增加一个选项。这不是ol3依赖的。

代码语言:javascript
复制
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;
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26071490

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档