-
Notifications
You must be signed in to change notification settings - Fork 23
/
reverseGeocode.py
159 lines (136 loc) · 6.01 KB
/
reverseGeocode.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
"""
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
import os
import re
import json
from qgis.PyQt import uic
from qgis.PyQt.QtWidgets import QDockWidget
from qgis.PyQt.QtGui import QColor
from qgis.PyQt.QtCore import Qt, QUrl, pyqtSignal, QByteArray, QEventLoop, QTextCodec
from qgis.core import QgsCoordinateReferenceSystem, QgsCoordinateTransform, QgsGeometry, QgsNetworkAccessManager, QgsProject, QgsNetworkContentFetcher, QgsWkbTypes
from qgis.gui import QgsMapTool, QgsRubberBand, QgsVertexMarker
from qgis.PyQt.QtNetwork import QNetworkRequest, QNetworkReply
FORM_CLASS, _ = uic.loadUiType(os.path.join(
os.path.dirname(__file__), 'reverseGeocode.ui'))
class ReverseGeocodeTool(QgsMapTool):
def __init__(self, iface, settings):
self.canvas = iface.mapCanvas()
QgsMapTool.__init__(self, self.canvas)
self.iface = iface
self.settings = settings
self.reverseGeoCodeDialog = ReverseGeocodeDialog(self, self.iface, self.iface.mainWindow())
self.iface.addDockWidget(Qt.TopDockWidgetArea, self.reverseGeoCodeDialog)
self.reverseGeoCodeDialog.hide()
self.epsg4326 = QgsCoordinateReferenceSystem('EPSG:4326')
self.marker = None
# Set up a polygon/line rubber band
self.rubber = QgsRubberBand(self.canvas)
self.rubber.setColor(QColor(255, 70, 0, 200))
self.rubber.setWidth(5)
self.rubber.setBrushStyle(Qt.NoBrush)
def activate(self):
'''When activated set the cursor to a crosshair.'''
self.canvas.setCursor(Qt.CrossCursor)
self.show()
def unload(self):
self.iface.removeDockWidget(self.reverseGeoCodeDialog)
self.reverseGeoCodeDialog = None
if self.rubber:
self.canvas.scene().removeItem(self.rubber)
del self.rubber
self.removeMarker()
def addMarker(self, lat, lon):
if self.marker:
self.removeMarker()
canvasCrs = self.canvas.mapSettings().destinationCrs()
transform = QgsCoordinateTransform(self.epsg4326, canvasCrs, QgsProject.instance())
center = transform.transform(lon, lat)
self.marker = QgsVertexMarker(self.canvas)
self.marker.setCenter(center)
self.marker.setColor(QColor(255, 70, 0))
self.marker.setIconSize(15)
self.marker.setIconType(QgsVertexMarker.ICON_X)
self.marker.setPenWidth(3)
self.marker.show()
def removeMarker(self):
if self.marker:
self.canvas.scene().removeItem(self.marker)
self.marker = None
def clearSelection(self):
self.removeMarker()
self.rubber.reset()
def transform_geom(self, geometry):
canvasCrs = self.canvas.mapSettings().destinationCrs()
geom = QgsGeometry(geometry)
geom.transform(QgsCoordinateTransform(self.epsg4326, canvasCrs, QgsProject.instance()))
return geom
def show(self):
self.reverseGeoCodeDialog.show()
def request(self, url):
fetcher = QgsNetworkContentFetcher()
fetcher.fetchContent(QUrl(url))
evloop = QEventLoop()
fetcher.finished.connect(evloop.quit)
evloop.exec_(QEventLoop.ExcludeUserInputEvents)
fetcher.finished.disconnect(evloop.quit)
return fetcher.contentAsString()
def canvasReleaseEvent(self, event):
# Make sure the point is transfored to 4326
self.clearSelection()
pt = self.toMapCoordinates(event.pos())
canvasCRS = self.canvas.mapSettings().destinationCrs()
transform = QgsCoordinateTransform(canvasCRS, self.epsg4326, QgsProject.instance())
pt = transform.transform(pt.x(), pt.y())
url = '{}?format=json&lat={:f}&lon={:f}&zoom={:d}&addressdetails=0&polygon_text=1'.format(self.settings.reverseURL(), pt.y(), pt.x(), self.settings.levelOfDetail)
# print( url )
jsondata = self.request(url)
try:
jd = json.loads(jsondata)
try:
display_name = jd['display_name']
self.setText(display_name)
except KeyError:
self.setText("[Could not find address]")
try:
wkt = jd['geotext']
geometry = QgsGeometry.fromWkt(wkt)
if geometry.wkbType() == QgsWkbTypes.Point:
pt = geometry.asPoint()
lon = pt.x()
lat = pt.y()
self.addMarker(lat, lon)
else:
geometry = self.transform_geom(geometry)
self.rubber.addGeometry(geometry, None)
self.rubber.show()
except KeyError:
try:
lon = float(jd['lon'])
lat = float(jd['lat'])
self.addMarker(lat, lon)
except:
pass
except Exception:
self.setText("Error: "+jsondata)
if not self.reverseGeoCodeDialog.isVisible():
self.show()
def setText(self, text):
self.reverseGeoCodeDialog.addressLineEdit.setText(text)
class ReverseGeocodeDialog(QDockWidget, FORM_CLASS):
closingPlugin = pyqtSignal()
def __init__(self, tool, iface, parent):
super(ReverseGeocodeDialog, self).__init__(parent)
self.setupUi(self)
self.tool = tool
def closeEvent(self, event):
self.tool.clearSelection()
self.closingPlugin.emit()
event.accept()