- QGIS Python Programming Cookbook
- Joel Lawhead
- 313字
- 2021-07-23 19:48:54
Measuring the distance between two points
In the QgsDistanceArea
object, PyQGIS has excellent capabilities for measuring the distance. We'll use this object for several recipes, starting with measuring the distance between two points.
Getting ready
If you don't already have the New York City Museums layer used in the previous recipes in this chapter, download the layer from https://geospatialpython.googlecode.com/svn/NYC_MUSEUMS_GEO.zip.
Unzip that file and place the shapefile's contents in a directory named nyc
within your qgis_data
directory, within your root or home directory.
How to do it...
In the following steps, we'll extract the first and last points in the layer's point order and measure their distance:
- First, import the library that contains the QGIS contents:
from qgis.core import QGis
- Then, load the layer:
lyr = QgsVectorLayer("/qgis_data/nyc/NYC_MUSEUMS_GEO.shp", "Museums", "ogr")
- Access the features:
fts = lyr.getFeatures()
- Get the first feature:
first = fts.next()
- Set a placeholder for the last feature:
last = fts.next()
- Iterate through the features until you get the last one:
for f in fts: last = f
- Create a measurement object:
d = QgsDistanceArea()
- Measure the distance:
m = d.measureLine(first.geometry().asPoint(), last.geometry().asPoint())
- Convert the measurement value from decimal degrees to meters:
d.convertMeasurement(m, 2, 0, False)
- Ensure that your Python console output looks similar to this tuple:
(4401.1622240174165, 0)
How it works...
The QgsDistanceArea
object accepts different types of geometry as input. In this case, we use two points. The map units for this layer are in decimal degrees, which isn't meaningful for a distance measurement. So, we use the QgsDistanceArea.convertMeasurement()
method to covert the output to meters. The parameters for the method are the measurement output, the input units (in decimal degrees), the output units (meters), and a boolean to denote whether this conversion is an area calculation verses a linear measurement.
The returned tuple is the measurement value and the units. The value 0 tells us that the output is in meters.
- jQuery EasyUI網站開發實戰
- Animate CC二維動畫設計與制作(微課版)
- Scratch真好玩:教小孩學編程
- 小程序,巧運營:微信小程序運營招式大全
- Creating Data Stories with Tableau Public
- Django 3.0應用開發詳解
- Clojure for Java Developers
- Practical GIS
- Distributed Computing with Python
- 微信公眾平臺開發最佳實踐
- 軟件再工程:優化現有軟件系統的方法與最佳實踐
- Analytics for the Internet of Things(IoT)
- Python深度學習:基于PyTorch
- Web前端開發全程實戰:HTML5+CSS3+JavaScript+jQuery+Bootstrap
- 面向對象程序設計及C++實驗指導(第3版)