- QGIS Python Programming Cookbook
- Joel Lawhead
- 243字
- 2021-07-23 19:48:54
Measuring the distance along a line sample
In this recipe, we'll measure the distance along a line with multiple vertices.
Getting ready
For this recipe, we'll use a line shapefile with two features. You can download the shapefile as a .ZIP
file from https://geospatialpython.googlecode.com/svn/paths.zip
Unzip the shapefile into a directory named qgis_data/shapes
within your root or home directory.
How to do it...
The steps for this recipe are fairly straightforward. We'll extract the geometry from the first line feature and pass it to the measurement object, as shown here:
- First, we must load the QGIS constants library:
from qgis.core import QGis
- Load the line layer:
lyr = QgsVectorLayer("/qgis_data/shapes/paths.shp", "Route", "ogr")
- Grab the features:
fts = lyr.getFeatures()
- Get the first feature:
route = fts.next()
- Create the measurement object instance:
d = QgsDistanceArea()
- Then, we must configure the QgsDistanceArea object to use the ellipsoidal mode for accurate measurements in meters:
d.setEllipsoidalMode(True)
- Pass the line's geometry to the
measureLine
method:m = d.measureLine(route.geometry().asPolyline())
- Convert the measurement output to miles:
d.convertMeasurement(m, QGis.Meters, QGis.NauticalMiles, False)
Ensure that your output looks similar to the following:
(2314126.583384674, 7)
How it works...
The QgsDistanceArea object can perform any type of measurement, based on the method you call. When you convert the measurement from meters (represented by 0) to miles (identified by the number 7), you will get a tuple with the measurement in miles and the unit identifier. The QGIS API documentation shows the values for all the unit constants
- 數據科學實戰手冊(R+Python)
- JavaScript全程指南
- 計算機圖形學編程(使用OpenGL和C++)(第2版)
- 摩登創客:與智能手機和平板電腦共舞
- FFmpeg入門詳解:音視頻流媒體播放器原理及應用
- 編寫高質量代碼:改善Python程序的91個建議
- Web Application Development with MEAN
- PHP+MySQL+Dreamweaver動態網站開發實例教程
- 輕松上手2D游戲開發:Unity入門
- Python數據可視化之美:專業圖表繪制指南(全彩)
- ASP.NET本質論
- Cinder:Begin Creative Coding
- KnockoutJS Blueprints
- JSP編程教程
- 快速搞定Spring Boot+Vue全棧開發