Performing nearest neighbor analysis

Nearest neighbor analysis relates one point to the nearest point in one or more datasets. In this recipe, we'll relate one set of points to the closest point from another dataset. In this case, we'll find the closest major city for each entry in a catalog of unidentified flying object (UFO) sightings from the National UFO reporting center. This analysis will tell you which major cities have the most UFO activity. The UFO catalog data just contains latitude and longitude points, so we'll use nearest neighbor analysis to assign names to places.

Getting ready

Download the following ZIP file and extract it to a directory named ufo in your qgis_data directory:

https://geospatialpython.googlecode.com/svn/ufo.zip

You will also need the MMQGIS plugin:

  1. From the QGIS Plugins menu, select Manage and Install Plugins….
  2. In the Plugins dialog search box, search for mmqgis.
  3. Select the MMQGIS plugin and click on the Install plugin button.

How to do it...

This recipe is simple. Here, we will load the layers and run the nearest neighbor algorithm within the MMQGIS plugin, as follows:

  1. First, we'll import the MMQGIS plugin:
    from mmqgis import mmqgis_library as mmqgis
    
  2. Next, as shown here, we'll load all our datasets:
    srcPath = "/qgis_data/ufo/ufo-sightings.shp"
    dstPath = "/qgis_data/ufo/major-cities.shp"
    usPth = "/qgis_data/ufo/continental-us.shp"
    output = "/qgis_data/ufo/alien_invasion.shp"
    srcName = "UFO Sightings"
    dstName = "Major Cities"
    usName = "Continental US"
    source = QgsVector(srcPath, srcName, "ogr")
    dest = QgsVector(dstPath, dstName, "ogr")
    us = QgsVector(usPath, usName, "ogr")
    
  3. Finally, we'll run and load the algorithm, which will draw lines from each UFO sighting point to the nearest city:
    mmqgis.mmqgis_hub_distance(iface, srcName, dstName, "NAME", "Miles", True, output, True)
    

How it works...

There are a couple of different nearest neighbor algorithms in QGIS, but the MMQGIS version is an excellent implementation and has the best visualization. Like the other recipes in this chapter, the plugin doesn't have an intentional Python API, so a good way to explore its functionality is to use the GUI interface before taking a look at the Python code. The following image shows the output, with UFO sightings represented by smaller points and hub lines leading to the cities, which are represented by larger, darker points.

How it works...
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset