Skip to content

Instantly share code, notes, and snippets.

@seydakucuk
Last active March 17, 2022 06:34
Show Gist options
  • Save seydakucuk/4d11a73b9befcfa0248f36b24425e258 to your computer and use it in GitHub Desktop.
Save seydakucuk/4d11a73b9befcfa0248f36b24425e258 to your computer and use it in GitHub Desktop.
Converts WGS84 coordinate to Web Mercator Coordinate using NetTopology Suite in C# .Net 6.0
using ProjNet.CoordinateSystems.Transformations;
double wgs84Longitude = 32.889242;
double wgs84Latitude = 38.959570;
var result = CoordinateConverter.ConvertWGS84ToWebMercator(wgs84Longitude, wgs84Latitude);
Console.Write(result.X + " " + result.Y);
public class CoordinateConverter
{
public CoordinateConverter()
{
NetTopologySuite.NtsGeometryServices.Instance = new NetTopologySuite.NtsGeometryServices(
NetTopologySuite.Geometries.Implementation.CoordinateArraySequenceFactory.Instance,
new NetTopologySuite.Geometries.PrecisionModel(1000d),
4326,
NetTopologySuite.Geometries.GeometryOverlay.NG,
new NetTopologySuite.Geometries.CoordinateEqualityComparer());
}
public static NetTopologySuite.Geometries.Point ConvertWGS84ToWebMercator(double WGS84Longitude, double WGS84Latitude)
{
var gf = NetTopologySuite.NtsGeometryServices.Instance.CreateGeometryFactory(4326);
var WGS84Point = gf.CreatePoint(new NetTopologySuite.Geometries.Coordinate(WGS84Longitude, WGS84Latitude));
var sourceCoordSystem = ProjNet.CoordinateSystems.GeographicCoordinateSystem.WGS84;
var targetCoordSystem = ProjNet.CoordinateSystems.ProjectedCoordinateSystem.WebMercator;
var WGS84toWebMercatorTransformation = new CoordinateTransformationFactory().CreateFromCoordinateSystems(sourceCoordSystem, targetCoordSystem);
var webMercatorPoint = Transform(WGS84Point, WGS84toWebMercatorTransformation.MathTransform);
return (NetTopologySuite.Geometries.Point)webMercatorPoint;
}
private static NetTopologySuite.Geometries.Geometry Transform(NetTopologySuite.Geometries.Geometry geom, MathTransform transform)
{
geom = geom.Copy();
geom.Apply(new MTF(transform));
return geom;
}
sealed class MTF : NetTopologySuite.Geometries.ICoordinateSequenceFilter
{
private readonly MathTransform _mathTransform;
public MTF(MathTransform mathTransform) => _mathTransform = mathTransform;
public bool Done => false;
public bool GeometryChanged => true;
public void Filter(NetTopologySuite.Geometries.CoordinateSequence seq, int i)
{
double x = seq.GetX(i);
double y = seq.GetY(i);
double z = seq.GetZ(i);
_mathTransform.Transform(ref x, ref y, ref z);
seq.SetX(i, x);
seq.SetY(i, y);
seq.SetZ(i, z);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment