OpenLayers : How to calculate distance between two points?

Jimmy picture Jimmy · Apr 11, 2012 · Viewed 17.8k times · Source

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

Thanks

Answer

Ramesh Kotha picture Ramesh Kotha · Apr 11, 2012

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);
    }