【问题标题】:OpenLayers : How to calculate distance between two points?OpenLayers:如何计算两点之间的距离?
【发布时间】:2012-04-11 15:59:29
【问题描述】:

如何在 OpenLayers 中使用墨卡托投影计算两点之间的距离?

谢谢

【问题讨论】:

    标签: openlayers distance points mercator


    【解决方案1】:

    使用point1.distanceTo(point2)

    var Geographic  = new OpenLayers.Projection("EPSG:4326"); 
    var Mercator = new OpenLayers.Projection("EPSG:900913");
    
    
    function distanceBetweenPoints(latlng1, latlng2){
            var point1 = new OpenLayers.Geometry.Point(latlng1.lon, latlng1.lat).transform(Geographic, Mercator);
            var point2 = new OpenLayers.Geometry.Point(latlng2.lon, latlng2.lat).transform(Geographic, Mercator);       
            return point1.distanceTo(point2);
        }
    

    【讨论】:

      【解决方案2】:

      如果使用 openlayers3

      ,您可以使用该方法

      在两点之间实例化一个 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;
              }
      

      【讨论】:

        【解决方案3】:

        尝试getLength 获取几何的球面长度:

        import LineString from 'ol/geom/LineString';
        import {getLength} from 'ol/sphere';
        
        const line = new LineString([coordStart, coordEnd]);
        const distance = getLength(line); 
        

        API:https://openlayers.org/en/latest/apidoc/module-ol_sphere.html#.getLength

        【讨论】:

        • 请在您的答案中添加一些解释,以便其他人可以从中学习
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-10-30
        • 2011-04-23
        • 2014-11-14
        • 1970-01-01
        相关资源
        最近更新 更多