Skip to content

Instantly share code, notes, and snippets.

@kampar
Last active June 21, 2022 09:50
Show Gist options
  • Save kampar/66acb0008c0dc5790e8932408d332c1e to your computer and use it in GitHub Desktop.
Save kampar/66acb0008c0dc5790e8932408d332c1e to your computer and use it in GitHub Desktop.
Create fields of 1000, 2500 and 5000 map scale bounding width and height for every feature on active layer. Currently using UTM Zone 47N for tranformation.
# layer to hold our current selected active layer
layer = iface.activeLayer()
#create new fields: skala1000w,skala1000h, ...
layer.dataProvider().addAttributes([QgsField("skala1000w",QVariant.Int),QgsField("skala1000h",QVariant.Int),QgsField("skala2500w",QVariant.Int),QgsField("skala2500h",QVariant.Int),QgsField("skala5000w",QVariant.Int),QgsField("skala5000h",QVariant.Int)])
# save all the changes
layer.updateFields()
# expression to be executed into corresponding field
expression_skala1000w = QgsExpression('ceil(bounds_width( transform( $geometry ,\'EPSG:4326\',\'EPSG:32647\')))')
expression_skala1000h = QgsExpression('ceil(bounds_height( transform( $geometry ,\'EPSG:4326\',\'EPSG:32647\')))')
expression_skala2500w = QgsExpression('ceil(bounds_width( transform( $geometry ,\'EPSG:4326\',\'EPSG:32647\'))/2.5)')
expression_skala2500h = QgsExpression('ceil(bounds_height( transform( $geometry ,\'EPSG:4326\',\'EPSG:32647\'))/2.5)')
expression_skala5000w = QgsExpression('ceil(bounds_width( transform( $geometry ,\'EPSG:4326\',\'EPSG:32647\'))/5)')
expression_skala5000h = QgsExpression('ceil(bounds_height( transform( $geometry ,\'EPSG:4326\',\'EPSG:32647\'))/5)')
context = QgsExpressionContext()
context.appendScopes(QgsExpressionContextUtils.globalProjectLayerScopes(layer))
with edit(layer):
for f in layer.getFeatures():
context.setFeature(f)
f['skala1000w'] = expression_skala1000w.evaluate(context)
f['skala1000h'] = expression_skala1000h.evaluate(context)
f['skala2500w'] = expression_skala2500w.evaluate(context)
f['skala2500h'] = expression_skala2500h.evaluate(context)
f['skala5000w'] = expression_skala5000w.evaluate(context)
f['skala5000h'] = expression_skala5000h.evaluate(context)
layer.updateFeature(f)
#tampilkan notifikasi
iface.messageBar().pushMessage("Sukses", "Menjalankan Ekspresi" ,level= Qgis.Success)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment