QGIS map tips allow you to hover the mouse cursor over a feature in order to create a popup that displays information. This information is normally a data field, but you can also display other types of information using a subset of HTML tags. In this recipe, we'll create an HTML map tip that displays a Google Street View image at the feature's location.
In your qgis_data
directory, create a directory named tmp
.
You will also need to download the following zipped shapefile and place it in your qgis_data/nyc
directory:
https://geospatialpython.googlecode.com/files/NYC_MUSEUMS_GEO.zip
We will create a function to process the Google data and register it as a QGIS function. Then, we'll load the layer and set its map tip display field. To do this, we need to perform the following steps:
from qgis.utils import qgsfunction from qgis.core import QGis import urllib
0
, means that the function won't accept any arguments itself. The second argument, Python
, defines the group in which the function will appear when you use the expression builder:@qgsfunction(0, "Python")
def googleStreetView(values, feature, parent): x,y = feature.geometry().asPoint() baseurl = "https://maps.googleapis.com/maps/api/streetview?" w = 400 h = 400 fov = 90 heading = 235 pitch = 10 params = "size=%sx%s&" % (w,h) params += "location=%s,%s&" % (y,x) params += "fov=%s&heading=%s&pitch=%s" % (fov, heading, pitch) url = baseurl + params tmpdir = "/qgis_data/tmp/" img = tmpdir + str(feature.id()) + ".jpg" urllib.urlretrieve(url, img) return img
pth = "/qgis_data/nyc/nyc_museums_geo.shp" lyr = QgsVectorLayer(pth, "New York City Museums", "ogr")
lyr.setDisplayField('<img src="[% $googleStreetView %]"/>')
QgsMapLayerRegistry.instance().addMapLayer(lyr)
The key to this recipe is the @qgsfunction
decorator. When you register the function in this way, it shows up in the menus for Python functions in expressions. The function must also have the parent and value parameters, but we didn't need them in this case.
The following screenshot shows a Google Street View map tip: