biglimp / PhDCourseVT2021

This repo include teaching materials for the PhD-course "Automate your GIS - Scripting in Python" (NGEO306)
7 stars 1 forks source link

Struggling with a loop #2

Open xdawst opened 3 years ago

xdawst commented 3 years ago

I've managed to write a working loop that (I think) calculates the distance between each vector point of one layer val_lokaler and each vector point of another layer centroids .

for x in val_lokaler.getFeatures():
    x_geom = x.geometry()
    for y in centroids.getFeatures():
        y_geom = y.geometry()
        dist_m = y_geom.distance(x_geom)
        print(x.id(), y.id(), dist_m)

However, what I want to do is calculate the distance between each point in val_lokaler and one specific point in centroids . The point it should calculate the distance from shares a common field and value in both layers (VALDISTRIK = e.g. 1234). I think I only need one loop for this (not the nested loop) but I can't figure out how to access the corresponding points in the centroid layer.

Thanks for your help!

biglimp commented 3 years ago

Cant you flip the loop and add a if statement?

for centroids:
   for vallokaler:
       if VALDISTRIKT==some number:
             calculate distance
biglimp commented 3 years ago

Let me know if you want to talk

xdawst commented 3 years ago

Great, thanks! I think it has worked with the following:

for i in centroids.getFeatures():
    i_geom = i.geometry()
    for j in val_lokaler.getFeatures():
        j_geom = j.geometry()
        if i['VALDISTRIK']==j['VALDISTRIK']:
            distance_m = i_geom.distance(j_geom)
            print(i.id(), j.id(), distance_m)  

It's printing the correct number of results, which is a good sign! Does this look coherent to you?

biglimp commented 3 years ago

Looks good. Why dont you measure manually in the map canvas to check if you are correct.