Open In App

Geospatial Queries with Python MongoDB

Prerequisites: MongoDB and Python

GeoJSON is an open-source format containing simple geographical features and is based on JavaScript Object Notation. It is used to format shapes in a coordinate space and multiple types are supported by MongoDB to permit storing geospatial data. This article will cover the various ways of using geospatial in MongoDB and explain the GeoJSON polygon and point types.



 
GeoJSON format



Note: If specifying latitude and longitude coordinates, list the longitude first and then latitude.

Modules Needed:

Steps to use MongoDB Atlas:

Below is the implementation.




import pymongo
import pprint
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
   
      
course_cluster_uri = 'your_connection_string'
   
course_client = pymongo.MongoClient(course_cluster_uri)
  
# sample Database
db = course_client['sample_geospatial']
  
# sample Collection
shipwrecks = db['shipwrecks']
   
l = list(shipwrecks.find({}))
   
lngs = [x['londec'] for x in l]
lats = [x['latdec'] for x in l]
   
# Clear the figure (this is nice if you
# execute the cell multiple times)
plt.clf()
   
# Set the size of our figure
plt.figure(figsize =(14, 8))
   
# Set the center of our map with our 
# first pair of coordinates and set
# the projection
m = Basemap(lat_0 = lats[0],
            lon_0 = lngs[0],
            projection ='cyl')
   
# Draw the coastlines and the states
m.drawcoastlines()
m.drawstates()
   
# Convert our coordinates to the system
# that the projection uses
x, y = m(lngs, lats)
   
# Plot our converted coordinates
plt.scatter(x, y)
   
# Display our beautiful map
plt.show()

Output:

shipwrecks plot


Article Tags :