Anzeem S N
Anzeem S N

Reputation: 151

How to get the distance of two point geometry in meters using NetTopologySuite?

How to get the distance of two point geometry in meters using NetTopologySuite.

I have used the Distance() function, but I'm getting some values and I couldn't identify the unit of those values. Its for a c# application to neglect the tolerance value of 20 meters to be ignored.

using NetTopologySuite.Geometries;
using GeoAPI.Geometries;

private static double findistance()
{
   var geomFactory = new GeometryFactory(new PrecisionModel(), 4326);
   IGeometry geometry1 = geomFactory.CreatePoint(new Coordinate(12.977299, 77.571075));
   IGeometry geometry2 = geomFactory.CreatePoint(new Coordinate(12.977277, 77.571258));
   var distance = geometry1.Distance(geometry2);
   return distance;
}

I need to get the distance calculated in meters.

Upvotes: 5

Views: 3579

Answers (2)

Yehor Androsov
Yehor Androsov

Reputation: 6152

Per docs, SRID 4326 stands for definition below

GEOGCS["WGS 84",
  DATUM["WGS_1984",
    SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],
    AUTHORITY["EPSG","6326"]],
  PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],
  UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],
  AUTHORITY["EPSG","4326"]]

UNIT["degree"... tells us that the result you are getting has values in degrees. We can calculate distance in meters, if we transform these points into Projected Coordinated system. ProjNET4GeoAPI package could do that for us.

private static double findDistance()
{
    CoordinateTransformationFactory ctfac = new CoordinateTransformationFactory();

    var from = GeographicCoordinateSystem.WGS84;
    var to = ProjectedCoordinateSystem.WebMercator;

    var trans = ctfac.CreateFromCoordinateSystems(from, to);
    var mathTransform = trans.MathTransform;

    var p1Coordinate = new GeoAPI.Geometries.Coordinate(12.977299, 77.571075);
    var p2Coordinate = new GeoAPI.Geometries.Coordinate(12.977277, 77.571258);

    p1Coordinate = mathTransform.Transform(p1Coordinate);
    p2Coordinate = mathTransform.Transform(p2Coordinate);

    return p1Coordinate.Distance(p2Coordinate);
}

Upvotes: 1

mtol
mtol

Reputation: 9

you can use the Pythagoras theorem to calculate the distance.

Here are the steps:

  1. Get Deltas
    • double int deltaX = Math.Abs(point1.X - point2.X);
    • double int deltaY = Math.Abs(point1.Y - point2.Y);
  2. Pythagoras formula
    • double distance = Math.Sqrt((deltaX * deltaX) + (deltaY * deltaY));

If you want to calculate a 3D point it is the same steps except calculate the DeltaZ and then the formula is distance = X^2 + Y^2 + Z^2

Upvotes: 0

Related Questions