OpenLayers : How to calculate distance between two points?

前端 未结 2 1616
余生分开走
余生分开走 2021-02-14 02:40

How can one calculate the distance in OpenLayers between 2 points using Mercator projection?

Thanks

2条回答
  •  情歌与酒
    2021-02-14 03:06

    You can use that method if using openlayers3

    Instanciate a ol.geom.LineString object between the two points and calculate the length of the line:

            this.distanceBetweenPoints = function(latlng1, latlng2){
                var line = new ol.geom.LineString([latlng1, latlng2]);
                return Math.round(line.getLength() * 100) / 100;
            };
    

    You can then get a readable value using some formation:

            this.formatDistance = function(length) {
                if (length >= 1000) {
                    length = (Math.round(length / 1000 * 100) / 100) +
                    ' ' + 'km';
                } else {
                    length = Math.round(length) +
                    ' ' + 'm';
                }
                return length;
            }
    

提交回复
热议问题