官术网_书友最值得收藏!

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:

  1. First, we must load the QGIS constants library:
    from qgis.core import QGis
    
  2. Load the line layer:
    lyr = QgsVectorLayer("/qgis_data/shapes/paths.shp", "Route", "ogr")
    
  3. Grab the features:
    fts = lyr.getFeatures()
    
  4. Get the first feature:
    route = fts.next()
    
  5. Create the measurement object instance:
    d = QgsDistanceArea()
    
  6. Then, we must configure the QgsDistanceArea object to use the ellipsoidal mode for accurate measurements in meters:
    d.setEllipsoidalMode(True)
    
  7. Pass the line's geometry to the measureLine method:
    m = d.measureLine(route.geometry().asPolyline())
    
  8. 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

(http://qgis.org/api/classQGis.html).

主站蜘蛛池模板: 宁国市| 民县| 含山县| 乌鲁木齐市| 红原县| 宁远县| 山阴县| 康平县| 图木舒克市| 长汀县| 镇坪县| 临江市| 宁城县| 尉氏县| 高要市| 夹江县| 井陉县| 新昌县| 扶沟县| 孟州市| 余庆县| 铁力市| 濉溪县| 绥阳县| 镇原县| 白沙| 通化市| 中卫市| 马尔康县| 石渠县| 临沂市| 抚顺县| 九龙城区| 奇台县| 阜宁县| 涿州市| 玉龙| 南雄市| 上杭县| 施秉县| 台安县|