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.
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:
mmqgis
.This recipe is simple. Here, we will load the layers and run the nearest neighbor algorithm within the MMQGIS plugin, as follows:
from mmqgis import mmqgis_library as mmqgis
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")
mmqgis.mmqgis_hub_distance(iface, srcName, dstName, "NAME", "Miles", True, output, True)
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.