Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I retrieve the geometry coordinates of a NpgsqlTypes.PostgisGeometry type field from the NpgsqlDataReader?

.NET 4.5, C#, Npgsql 3.1.0

I have a query which retrieves a Postgis geometry field - the only way I could see of doing this was:

public class pgRasterChart
{
    ...
    public NpgsqlTypes.PostgisGeometry GEOMETRY;    
    ...
}
...
NpgsqlDataReader reader = command.ExecuteReader();
try
   {
       while (reader.Read())
       {
           pgRasterChart chart = new pgRasterChart();
           chart.GEOMETRY = (PostgisGeometry) reader.GetValue(21);
...

This functions but I need to get at the coordinates of the GEOMETRY field and I can't find a way of doing that? I want to use the coordinates to display the results on an OpenLayers map.

Any answers most gratefully received. This is my first post so my apologies if the etiquette is clumsy or question unclear.

like image 377
pdc Avatar asked Dec 19 '25 06:12

pdc


1 Answers

Providing another answer because the the link above to the documentation for PostGisTypes is now broken.

PostGisGeometry is an abstract base class that does not contain anything more exiting than the SRID. Instead, you want to cast the object obtained by your datareader to the appropriate type (any of the following):

  • PostGisLineString
  • PostGisMultiLineString
  • PostGisMultiPoint
  • PostGisMultiPolygon
  • PostGisPoint
  • PostGisPolygon

These classes have ways of getting to the coordinates.

eg:

...
NpgsqlDataReader reader = command.ExecuteReader();
try
   {
       while (reader.Read())
       {
           var geom = (PostgisLineString) reader.GetValue(0);
           var firstCoordinate = geom[0]; // Coordinate in linestring at index 0
           var X = firstCoordinate.X;
           var Y = firstCoordinate.Y;
...
like image 175
Emil G Avatar answered Dec 24 '25 07:12

Emil G



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!