2

I use Qgis. I have two layers that are two circles with the same center. One larger and one smaller. I want to do the difference between the two circles BUT only if they have the same "objectid" (the same id). So I have written this code: Layers

for features in itertools.product(elayer.getFeatures("objectid"), player.getFeatures("objectid")):
    id = tuple(feat.attributes()[0] for feat in features)
    print("elayer" ,id[0] , "player", id[1])
    if id[0] == id[1]:
        pass
        processing.runAndLoadResults("native:difference",
        {'INPUT':elayer(id[0]), 'OVERLAY': player(id[1]), 'OUTPUT':'memory:'})

where elayer and player are clearly the two layers. But this code makes me all differences between all geometries in the two layers. How can I adjust it in order to get what I want?

3

When you find a matching ID between two features, you can select them and then make use of the QgsProcessingFeatureSourceDefinition class which allows you to use selected features inside your processing algorithm.

You could try something like the following:

for features in itertools.product(elayer.getFeatures("objectid"), player.getFeatures("objectid")):
    id = tuple(feat.attributes()[0] for feat in features)
    print("elayer" ,id[0] , "player", id[1])
    if id[0] == id[1]:
        pass
        elayer.selectByExpression('\"objectid\" = ' + str(id[0]), QgsVectorLayer.SetSelection)
        player.selectByExpression('\"objectid\" = ' + str(id[1]), QgsVectorLayer.SetSelection)
        processing.runAndLoadResults("native:difference",
        {'INPUT':QgsProcessingFeatureSourceDefinition(elayer.id(), True), 
        'OVERLAY': QgsProcessingFeatureSourceDefinition(player.id(), True), 
        'OUTPUT':'memory:'})
3

You can achieve this using a virtual layer. You would join the two layers on their objectid and compute the difference between the matching geometries.

go to the menu Layer > Add Layer > Add/Edit Virtual Layer... and enter the following query. Feel free to add more fields from either layer.

SELECT st_difference(a.geometry, b.geometry) as geometry
FROM elayer a
  JOIN player b
     ON a.objectid = b.objectid

enter image description here

To illustrate it, the elayer is redish, player is blue and the virtual layer output is hatched. Note that the 4th polygon from player, which has a different objectid wasn't removed from the underlying polygon from elayer

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.