OpenLayer3的getArea()及getLenth()方法解析

来源:互联网 发布:已选中提示js代码 编辑:程序博客网 时间:2024/06/05 04:20

问题来源:为什么方法返回的数据不带单位?


通过在官网的measures例子发现,这种方法得到的值是没有意义的值,必须要通过设定好球体,才能得到相应的面积/长度。

改良版代码

适用于坐标系为4326的格式转换,若不是4326坐标系,就要自行参照官网的例子转换。(建议可以浏览ol.Sphere,只有两个函数
      /**       * Format length output.       * @param {ol.geom.LineString} line The line.       * @return {string} The formatted length.       */     function formatLength(line) {    var wgs84Sphere = new ol.Sphere(6378137);                var coordinates = line.getCoordinates();                var length = 0;            for (var i = 0, ii = coordinates.length - 1; i < ii; ++i) {                length += wgs84Sphere.haversineDistance(coordinates[i], coordinates[i+1]);            }        var output;        if (length > 100) {          output = (Math.round(length / 1000 * 100) / 100) +              ' ' + 'km';        } else {          output = (Math.round(length * 100) / 100) +              ' ' + 'm';        }        return output;     }     /**       * Format area output.       * @param {ol.geom.Polygon} polygon The polygon.       * @return {string} Formatted area.       */      function formatArea(polygon) {        var wgs84Sphere = new ol.Sphere(6378137);                var coordinates = polygon.getLinearRing(0).getCoordinates();                var area = Math.abs(wgs84Sphere.geodesicArea(coordinates));        var output;        if (area > 10000) {          output = (Math.round(area / 1000000 * 100) / 100) +              ' ' + 'km<sup>2</sup>';        } else {          output = (Math.round(area * 100) / 100) +              ' ' + 'm<sup>2</sup>';        }        return output;      },


0 0
原创粉丝点击