[GIS] distanceTo is giving wrong result in OpenLayers

coordinate systemdistanceopenlayers-2

I am using distanceTo from OpenLayers to calculate the distance between two locations

These are map details:

  Geographic  = new OpenLayers.Projection("EPSG:4326"); 
  Mercator = new OpenLayers.Projection("EPSG:900913");  

   map = new OpenLayers.Map({
   div: "map_canvas",
   projection: Mercator,
   displayProjection: Geographic,
   center: new OpenLayers.LonLat(0, 0),
   minResolution: "auto",
   minExtent: new OpenLayers.Bounds(-1, -1, 1, 1),
   maxResolution: "auto",
   maxExtent: new OpenLayers.Bounds(-180, -90, 180, 90),
   units : 'km'
});

these are my lat and lon values

lat = 47.162494, lon = 19.503304
lat = 46.2525684, lon = 20.147060499999952

google maps function result is 111861.5962110549

function distanceBetweenMarkers(latlng1, latlng2){
    return google.maps.geometry.spherical.computeDistanceBetween(latlng1, latlng2);
}

openlayers function result 6237980.800397318

function distanceBetweenMarkers(latlng1, latlng2){
        var point1 = new OpenLayers.Geometry.Point(latlng1.lon, latlng1.lat);
        var point2 = new OpenLayers.Geometry.Point(latlng2.lon, latlng2.lat);
        return point1.distanceTo(point2);
    }

Why is the difference between google maps computeDistanceBetween and openlayers distanceTo?

Best Answer

try to use getGeodesicLength.

it works for calculating the approximate length of the geometry were it projected onto the earth.

distanceTo method works for planar measure which handle the world as a flat using cartesian coordinates. getting approximately the accurate results , you should use geodesic measurament for your project.

var point1 = new OpenLayers.Geometry.Point(latlng1.lon, latlng1.lat);
var point2 = new OpenLayers.Geometry.Point(latlng2.lon, latlng2.lat);

var line = new OpenLayers.Geometry.LineString([p1, p2]);
alert(line.getGeodesicLength(new OpenLayers.Projection("EPSG:4326")));

i hope it helps you...

Related Question