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

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:

  1. First, import the library that contains the QGIS contents:
    from qgis.core import QGis
    
  2. Then, load the layer:
    lyr = QgsVectorLayer("/qgis_data/nyc/NYC_MUSEUMS_GEO.shp", "Museums", "ogr")
    
  3. Access the features:
    fts = lyr.getFeatures()
    
  4. Get the first feature:
    first = fts.next()
    
  5. Set a placeholder for the last feature:
    last = fts.next()
    
  6. Iterate through the features until you get the last one:
    for f in fts:
     last = f
    
  7. Create a measurement object:
    d = QgsDistanceArea()
    
  8. Measure the distance:
    m = d.measureLine(first.geometry().asPoint(), last.geometry().asPoint())
    
  9. Convert the measurement value from decimal degrees to meters:
    d.convertMeasurement(m, 2, 0, False)
    
  10. 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.

主站蜘蛛池模板: 赤城县| 湘潭市| 北流市| 木兰县| 竹山县| 尼木县| 连江县| 新乡市| 湖州市| 双城市| 香河县| 堆龙德庆县| 漳平市| 鄂温| 灵璧县| 高碑店市| 墨竹工卡县| 怀集县| 青河县| 呼伦贝尔市| 砚山县| 南陵县| 会理县| 新郑市| 班戈县| 南江县| 武清区| 礼泉县| 新闻| 湖口县| 玉山县| 龙陵县| 镇远县| 望都县| 伊吾县| 鲁甸县| 清河县| 洛南县| 永新县| 元阳县| 嘉义市|