0

I found this guide to get pixel value of raster under point: Getting pixel value of GDAL raster under OGR point without NumPy?

I've a problem here:

for feat in lyr:
    geom = feat.GetGeometryRef()
    mx,my=geom.GetX(), geom.GetY()  #coord in map units

If I print geom, I can see all the point's coordinates but if I print mx or my the result is 0 for every feat.

if I print geom:

MULTIPOINT (9.48556682927651 39.1368546561669)
MULTIPOINT (9.46173837787432 39.1298387934389)
MULTIPOINT (9.54058251881085 39.441437960101)
MULTIPOINT (9.08688113454087 39.5390542536278)
MULTIPOINT (9.00215692841357 39.0072908447031)
MULTIPOINT (9.17741005408364 39.2751570664614)

if i print mx or my:

0.0
0.0
0.0
0.0
0.0
0.0

I'm using Python 3 maybe this could be a problem

3

You have multipoint data, not points. You need to pull out the point geoms from the multipoints.

Assuming only a single point per multipoint (as per your example):

wkt = 'MULTIPOINT (9.48556682927651 39.1368546561669)'
multipoint = ogr.CreateGeometryFromWkt(wkt )
point = multipoint.GetGeometryRef(0) # <--- Get the point at index 0
print(point.GetX(), point.GetY())

If you don't want to assume only a single point, you can loop through the points in each multipoint:

wkt = 'MULTIPOINT (9.48556682927651 39.1368546561669, 9.46173837787432 39.1298387934389)'
multipoint = ogr.CreateGeometryFromWkt(wkt)
for i in range(multipoint.GetGeometryCount()):
    point = multipoint.GetGeometryRef(i) # <--- Get the geom at index i
    print(point.GetX(), point.GetY())

So when you're looping through the layer, do something like this:

for feat in lyr:
    multipoint = feat.GetGeometryRef()

    point = multipoint.GetGeometryRef(0) # <--- Get the point at index 0
    mx,my = point.GetX(), point.GetY()

    ## OR ##

    for i in range(multipoint.GetGeometryCount()):
        point = multipoint.GetGeometryRef(i) # <--- Get the geom at index i
        mx,my = point.GetX(), point.GetY()
-1

I write this and split the string

geom=feat.GetGeometryRef()
point=geom.Centroid().ExportToWkt() 
mx=float(point.split(' ')[1][1:len(point.split(' ')[1])])
my=float(point.split(' ')[2][0:len(point.split(' ')[2])-1])

Maybe someone will have this problem too

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.