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

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

通过在官网的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;
	      },

转载自:https://blog.csdn.net/u013323965/article/details/52701678

You may also like...