[OpenLayers-Dev] Get distance from point to point in meters

Tim Schaub tschaub at opengeo.org
Tue Mar 9 14:11:09 EST 2010

gingerbbm wrote:
> Are you familiar with the documentation? I've never had to do what you're
> asking but I've just seen the following which sounds like it might be useful
> to you.
> http://dev.openlayers.org/releases/OpenLayers-2.8/doc/apidocs/files/OpenLayers/Geometry/Point-js.html#OpenLayers.Geometry.Point.distanceTo

Yes, geometry.distanceTo is it.  This will return the distance between 
two geometries in map units (the units for the coordinates of your 
geometry).  If you want to convert to meters, you can do the conversion 
manually.  The distanceTo calculation is a planar measure (treating the 
coordinates of your geometry as Cartesian coordinates).

If you want to calculate the distance between two points on a spheriod 
(one approximating the earth's surface) instead of a plane (your 
coordinate reference system), then you want the geodesic distance.  This 
requires that you also have defined the projection (your coordinate 
reference system) and that coordinates can be transformed to a 
geographic projection client-side.

If you are using EPSG:4326, EPSG:900913, or if you have included the 
proj4js definition of your projection, then you can calculate the 
geodesic length of a linestring as follows:

     var dist = line.getGeodesicLength(projection);

The default projection is what you get from new 
OpenLayers.Projection("EPSG:4326").  The getGeodesicLength method 
returns a distance in *meters* (regardless of the units of your geometry 

If you have two point geometries and you want to do this calculation, 
you could do the following:

     var line = new OpenLayers.Geometry.LineString([p1, p2]);
     var dist = line.getGeodesicLength(projection);

Find the getGeodesicLength docs on the same page linked above.


Tim Schaub
OpenGeo - http://opengeo.org
Expert service straight from the developers.

More information about the Dev mailing list