Get startedGet started for free

Applying a custom operation to each geometry

Now we know how to get the closest national park for a single point, let's do this for all points. For this, we are first going to write a function, taking a single point as argument and returning the desired result. Then we can use this function to apply it to all points.

The datasets on the mining sites (mining_sites) and national parks (national_parks) are already loaded. The single mining site from the previous exercises is already defined as single_mine.

This exercise is part of the course

Working with Geospatial Data in Python

View Course

Exercise instructions

  • Create a function closest_national_park() that performs the analysis you did in the previous exercise: given a single point and all national parks, return the name of the closest national park.
  • As a test, call this function on the single point (single_mine) and print the result. Is it the same as before ("Virunga National park")?
  • Apply this function to all points of mining_sites and assign the result to a column called 'closest_park'.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Define a function that returns the closest national park
def closest_national_park(geom, national_parks):
    dist = ____
    idx = ____
    closest_park = ____
    return closest_park

# Call the function on single_mine
print(closest_national_park(____, ____))

# Apply the function to all mining sites
mining_sites['closest_park'] = mining_sites.geometry.____(____, ____=____)
print(mining_sites.head())
Edit and Run Code