How to store geo bounding box in Django database?

Published 7 Dec, 2021

Reading time: 2 Mins

In Djagno models database how do store geo location coordinates like multiple lattitude and longitude aka bounding box?

There is PointField in Django which is easy to store longitude and latitude in Django but what if I wanted to store Multiple lat, lng in the same record. Well, the answer is PolygonField. There is also another fields like multipoint and Geometry collection fields but for the bounding box PolygonField is the best. Create the models like this in your Django project.

from django.contrib.gis.models import PointField
class Zone(models.Model):
		geo = PolygonField(verbose_name="bounding box)

Now that we created the table and column it’s time to look into how we can use this to store the bounding box. Let’s say I wanted to store US state Alabama into the bounding box. First we need to get those coordinates, the best way we can do that using the geopy python package. It will come in handy and easily extendable to other providers. For sake of this blog I’m going to use Nominatim

from django.contrib.gis.geos import Point, GeometryCollection

geolocator = Nominatim(user_agent="demo")
location = geolocator.geocode({"state": "Alabama"})

You can take a look at the to read all of the providers and the method they offer. Here the location will provide the raw data and we can grab the boundingbox value from it.

boundingbox = location.raw.get("boundingbox")
lon1 = boundingbox[1]
lat1 = boundingbox[2]
lon2 = boundingbox[0]
lat2 = boundingbox[3]

southwest = Point(float(lon1), float(lat1))
norteast = Point(float(lon2), float(lat2))
rect = GeometryCollection(southwest, norteast).envelope

And then you can directly assign rect into the geo PolygonField.


Read More