Skip to content

Instantly share code, notes, and snippets.

@3nids
Last active September 4, 2015 04:20
Show Gist options
  • Save 3nids/7035856c5731ba6994fc to your computer and use it in GitHub Desktop.
Save 3nids/7035856c5731ba6994fc to your computer and use it in GitHub Desktop.
Simple QGIS geocoder
import geocoder
g = geocoder.google("[% "__MYADDRESSFIELD__" %]".replace("'", r"\'"))
if not g.latlng:
print "adress not found"
else:
pt = QgsPoint(g.latlng[1],g.latlng[0])
tr = QgsCoordinateTransform( QgsCoordinateReferenceSystem( 4326 , QgsCoordinateReferenceSystem.EpsgCrsId ),
QgsCoordinateReferenceSystem( __MYEPSG__, QgsCoordinateReferenceSystem.EpsgCrsId ))
pt = tr.transform( pt )
print pt.x(), pt.y()
layer = QgsMapLayerRegistry.instance().mapLayer("__MYLAYERID__")
if not layer or not layer.isEditable():
print "layer not found or not editable"
else:
layer.changeGeometry([% $id %], QgsGeometry.fromPoint(pt))
layer.updateExtents()
layer.setCacheImage(None)
layer.triggerRepaint()
@3nids
Copy link
Author

3nids commented Jun 10, 2015

This code allows you to define a layer action to set the geometry (point) based on an address field using Google geocoder.

  1. Install geocoder: pip install geocoder
  2. replace MYADDRESSFIELD, MYEPSG and MYLAYERID in the code
  3. paste this to actions of the desired layer (as a Python action)
  4. run action "GeoCode" for a feature

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment