Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenLayers : How to calculate distance between two points?

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

Thanks

like image 582
Jimmy Avatar asked Apr 11 '12 15:04

Jimmy


2 Answers

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;
        }
like image 45
Alexandre Mélard Avatar answered Sep 28 '22 23:09

Alexandre Mélard


use 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);
    }
like image 73
Ramesh Kotha Avatar answered Sep 28 '22 22:09

Ramesh Kotha