How to Create a Boundaries Geofencing App

RapidAPI Team
The Era of APIs
Published in
8 min readApr 21, 2020

Geographical data is a basic need for various different societal and business layers. For individual purposes, it’s a very useful way of navigation and travel coordination.

You may have situations when your entire route was mapped out on a geo application because you have never personally visited the destination before. But when you are a creator of some product, there is a necessity of interactive maps with your own marks.

It is a widespread practice in the retail, delivery services, banking (addresses of your departments), and many many more areas. So if you want to simplify the client’s interaction with a product, you should provide a geographical coordination system.

Boundaries API is a perfect way to set the mentioned feature on your platforms. So today we will be taking a look at an intelligent option for interactive map managing.

How to connect to the Boundaries-IO API

You can check the link to the chosen interface here. Don’ worry, you won’t be burdened with anything complicated and expensive. RapidAPI does all the communications by itself. The one and only required thing is registration on this platform.

You will have an opportunity to work with enormous APIs from one convenient location. Moreover, the majority of the interfaces offer free access to a basic usage plan. So let’s choose such an option for our current API.

It’s important to keep in mind that a basic plan includes only 10 free requests. This means that you have to be very careful with your experience at this stage. Yet, if you follow our steps, there is nothing to fear. The correct setting has been chosen, so now we can dive into the deep waters of boundaries API!

How to interpret and visualize GeoJSON data

Before we can do this by ourselves, we need to understand the entire format. GeoJSON is a standard form of geographical object recording. It’s based on a Javascript object notation. A GeoJSON allows storing and representing location data without other sources. This approach also has a unique characteristic. It was invented by independent developers with no commercial participation.

The main areas of implementation for the GeoJSON include geofencing, region highlightings, pointing of some exact places and combining of all previous features. Let’s describe basic entities within this notation.

  • Point — just a marked place on the map. A point is declared with longitude and latitude.
  • MultiPoint — a bunch of points. It is useful, for example, when you want to show all the accessible shops in the chosen region.
  • LineString — it is a line (or combination of consecutive lines), which shows the route.
  • Polygon — this is a geometric figure which creates a specific highlighted region. It can be used, as an example, in cases where you want to show the area of the city where deliveries are made from your restaurant.
  • FeatureCollection — this is an array of different GeoJSON subjects. Usually, this object dominates in the descriptions, because it allows creating all possible map structures.

Since this format is very popular, we can find many interactive editors for it. For example, let’s pick a geojson.io platform. Here we can test our objects and with instant visualization.

So let’s return to the boundaries API endpoints and click on the query by location. This request returns detailed information about the neighborhood and its specific coordinates. This is a very useful way to explain to the user where he/she is at the moment. You can test this endpoint in a very advanced working interface and even take a look at a sample response.

Here we can see the approximate response structure. First of all, the JSON object informs that it includes FeatureCollection. The next stage is about feature describing. Here the API returns some useful insights about the neighborhood. Finally, the result has a geometry dictionary with only one object — Polygon. Let’s copy this response example, and paste it directly to the geojson.io interface.

As you can see, the platform displays our object precisely. Even without any extra information on the polygon origin. It means that we have all the required tools for practical example creation. We can get some useful locations, save and represent them. Well, what are we waiting for?

How to create Geofencing Geolocation App on a Python and Jupyter Notebook

Python is a very cool language for API communication and response processing. It’s a scripting language, so we need to find someplace with visualization ability. And the Jupyter Notebook fits perfectly. This is a cross-platform environment for Python investigations with large demonstration opportunities.

  • Python — the main language of the project. You can use it directly from the system or create a virtual environment. We are true fans of the second option as it gives you a more separate and clear project area. Also, you will need to provide the pip presence. It is a tool for installing additional Python modules.
  • Jupyter Notebook — browser solution for the Python snippets execution. It is available as a single module, but also as a part of the Anaconda package.
  • geopandas — it is an analogue of the famous pandas’ library for Python. This package is able to work with geofencing on a very high level. You can parse some geojson/json files, get centroids for each object, and even count many different metrics. And the main benefit is that the syntax for the interaction tends to be very similar to that of Pandas.
  • geojsonio — as you may remember, we used this platform for object visualization. But we can also do this programmatically.
  • matplotlib — a module for chart visualization.
  • ipywidgets — special module for the Jupyter Notebook, which assists with creating interactive widgets within a file.
  • ipyleaflet — a Python version of the legendary leaflet JavaScript library. It has the ability to create maps directly in the Python output. But it won’t work without ipywidgets.
  • requests — one more side package, which makes HTTP requests with the API easier.

We won’t be concentrating on Jupyter usage specifics, so if you aren’t familiar with it, you can get some knowledge here.

Okay, let’s get started!

First of all, we need to understand the concept of the script. Since we have a very powerful geofencing aggregator for the US, we can simplify some tasks.

Let’s imagine that our company is a Post service. The boundaries API has a very informative endpoint for such cases. Here we can get zip codes for regions based on the request parameters. For example, we can type some specific city (or country, location, etc.) and retrieve all zip codes for it. So, our post worker will type a city title, and see the interactive map with all zip codes there.

Now, we need to run our Jupyter environment and create a new .ipynb file. Let’s establish the input from the user.

city = input('Type a city: ') city

Now it’s time to get a response from the boundaries API. Paste the following code to the new cell:

import requests url = "https://vanitysoft-boundaries-io-v1.p.rapidapi.com/reaperfire/rest/v1/public/boundary" querystring = {"city":city,"limit":"50"} headers = { 'x-rapidapi-host': "vanitysoft-boundaries-io-v1.p.rapidapi.com", 'x-rapidapi-key': "YOUR_RAPID_API_KEY" } response = requests.request("GET", url, headers=headers, params=querystring) print(response.text)

A practical hint: you can use a snippet for the HTTP interactions from the RapidAPI samples. This one was taken directly from the endpoint page.
Okay, now we have the desired data, but we need to provide an ability to reuse this object. Let’s save the response text to the .json file.

with open('city-zipcode.json', 'w') as f: f.writelines(response.text)

Now you can relax about data storing, especially in case of a hard limit for the requests to boundaries API. But let’s return to the GeoJSON processing. You basically have two options here: display the map on the geojson.io (with the ability to save it on the Github gist), or show it in the Jupyter file.

import geopandas as gpd salt_lake = gpd.read_file('city-zipcode.json') print(salt_lake.head())

You can see that geopandas processes data very well. Let’s do some light exploration of the new dataset.

Our dataset has 49 records because we set a limitation for lower than 50 zip codes. Each object has textual fields and geometrical description (in a GeoJSON format). Now let’s take a look at the official boundaries of Salt Lake City.

Okay, but we can compare this with our dataset just with a little plot.

import matplotlib.pyplot as plt salt_lake.plot(figsize=(15,13))

It is very interesting how zip codes don’t cover the same area as the official city borders. But, of course, we aren’t satisfied with such poor visualization.

import geojsonio geojsonio.display(salt_lake.to_json())

Now your browser should be redirected to the geojson.io tab with our dataset as an object. Let’s take a look at it.

Pretty good, right?

But even this result isn’t ideal.

A Post worker wouldn’t like to visit some other resource for the map visualization.

Now is the time for ipyleaflet. This beautiful library has everything you need to build nice maps. Furthermore, you can customize it with specific geometrical objects.

from ipyleaflet import Map, GeoJSON import json def getXY(pt): return (pt.x, pt.y) with open('city-zipcode.json', 'r') as f: data = json.load(f) centroid = getXY(salt_lake['geometry'].centroid) m = Map(center=(mean(centroid[1]), mean(centroid[0])), zoom=10) geo_json = GeoJSON(data=data, style = {'color': 'blue', 'opacity':1, 'weight':1.9, 'dashArray':'9', 'fillOpacity':0.1}) m.add_layer(geo_json) m

Now the Post worker should be satisfied!

This map isn’t just only interactive, but the program can be rebuilt for new GeoJSON objects, so there is no difficulty in determining the zip codes for Salt Lake City.

Conclusion

If the company wants to remove all boundaries with its clients, there is a need to use the boundaries API. Because the user experience will be more satisfying with map visualization and highlights. And we know that the chosen API can cover all these use cases very well.

All we’ve done here is a simple example of how the API works, which means that you can improve it or make something new. But even with our simple code, it is obvious how simple and fast GeoJSON rendering is.

Originally published at https://rapidapi.com on April 21, 2020.

--

--