0

Just starting with Python, plugins and actions in QGIS.

From an postal code api I get a position in WGS84: lat and lon.

I want my map (in WGS 84 pseudo-Mercator) to center on this point.

Since several hours I'm googling everywhere I have tried everything but to no avail.

My code now is (based on several answers on different forums since I've not seen the straight answer I need):

map_pos = QgsPoint(lon, lat)

map_pos.crs = QgsCoordinateReferenceSystem(4326)

rect = QgsRectangle(map_pos,map_pos)

self.iface.mapCanvas().setExtent(rect)

self.iface.mapCanvas().refresh()

I get this message:

rect = QgsRectangle(map_pos,map_pos) TypeError: QgsRectangle(): arguments did not match any overloaded call: overload 1: too many arguments overload 2: argument 1 has unexpected type 'QgsPoint' overload 3: argument 1 has unexpected type 'QgsPoint' overload 4: argument 1 has unexpected type 'QgsPoint' overload 5: argument 1 has unexpected type 'QgsPoint'

Question: how to center the map on a point while their crs differ? Should be very simple!

1

The source of the error is that you are passing QgsPoint objects to the QgsRectangle constructor when it is expecting QgsPointXY objects. But you are also trying to create a rectangle from two identical points.

If you want to center the canvas on a point, then I recommend using the setCenter() method with a QgsPointXY rather than using setExtent() with a QgsRectangle.

To overcome the differing CRS you can use the QgsCoordinateTransform class to transform the point from epsg:4326 to epsg:3857.

After calling setCenter() you can also set the zoom level by calling zoomScale() and passing an appropriate value.

Try the code below:

map_pos = QgsPointXY(lon, lat)
src_crs = QgsCoordinateReferenceSystem(4326)
dest_crs = QgsCoordinateReferenceSystem(3857)
xform = QgsCoordinateTransform(src_crs, dest_crs, QgsProject().instance())
map_pos = xform.transform(map_pos)
self.iface.mapCanvas().setCenter(map_pos)
# set scale if desired
self.iface.mapCanvas().zoomScale(1500000)
self.iface.mapCanvas().refresh()

Alternatively, if you still want to use setExtent(), you would have to do something like the following:

r_min = QgsPointXY(lon-0.5, lat-0.5)
r_max = QgsPointXY(lon+0.5, lat+0.5)
rect = QgsRectangle(r_min, r_max)
src_crs = QgsCoordinateReferenceSystem(4326)
dest_crs = QgsCoordinateReferenceSystem(3857)
xform = QgsCoordinateTransform(src_crs, dest_crs, QgsProject().instance())
rect = xform.transform(rect)
self.iface.mapCanvas().setExtent(rect)
self.iface.mapCanvas().refresh()

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.