Open Source Mapping with Python, and MongoDB

techprane 69 views 27 slides Oct 08, 2024
Slide 1
Slide 1 of 27
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27

About This Presentation

How to use MongoDB's Geospatial capabilities. We examine 2dSphere and 2d indexes.


Slide Content

Samuel Folasayo Geospatial Mapping with Python, and MongoDB Building a Web Application Visualize MongoDB Geospatial Data Joe Nyirenda

Geospatial Data in MongoDB GeoJSON Data about location Cartesian - small distances 2d sphere - larger distances Define shapes, points, lines Can be (x,y) coordinates or latitude /longitude Use cases Location-based services Mapping and visualization Proximity search Real-time tracking

M ongoDB supports geospatial indexing for storing and querying location data. Geospatial indexes efficiently query documents based on their geographical location. Two main types: 2dsphere and 2d indexes. MongoDB Geospatial Features

Real-world Applications : Mapping (Google Maps, Uber). Proximity Search (finding nearby stores/services). Routing (shortest path between locations). MongoDB Advantages : Efficiently stores and queries geospatial data. Highly scalable and flexible for managing large datasets. Benefits of Using Geospatial Data

Urban Planning Environmental Monitoring Business Intelligence Disaster Management Use Cases of Geospatial Data

Examples of Geospatial Data Latitude and longitude coordinates. Locations of restaurants, landmarks, and cities. Routes or paths (e.g., hiking trails, bus routes). Satellite imagery and geographic boundaries (like country borders). geo_database > db .places. find () [ { _id: ObjectId( '66fbd265fa70425c15b81b11' ), name: 'Statue of Liberty' , location: { type : 'Point' , coordinates: [ - 74.0445 , 40.6892 ] } }, { _id: ObjectId( '66fbd265fa70425c15b81b12' ), name: 'Eiffel Tower' , location: { type : 'Point' , coordinates: [ 2.294481 , 48.85837 ] } } ]

2dsphere Index: Used for querying data in spherical geometry (e.g., Earth’s curvature). Supports geometries like Points, Lines, and Polygons. 2d Index: Designed for flat, Euclidean geometry. Best for legacy applications or when modeling flat coordinates. Types of Geospatial Indexes

To create these indexes in MongoDB: 2dsphere Index: db.places.createIndex({ location: "2dsphere" }) 2d Index: db.places.createIndex({ location: "2d" } ) Explanation: 2dsphere supports complex geospatial queries on Earth’s surface. 2d is simpler and for flat data, often used in older systems. Creating Geospatial Indexes

2dsphere Index : Use when dealing with spherical data (e.g., latitude and longitude for Earth). 2d Index : Use for flat, Cartesian data, or when spherical accuracy is not required. When to Use 2dsphere and 2d Index

MongoDB uses GeoJSON format for storing geographic data. GeoJSON represents geographic features like points, lines, and polygons. Allows the use of complex geospatial queries like $geoWithin , $near , and $geoIntersects . GeoJSON in MongoDB

Create a 2dsphere index on the location field in MongoDB. Perform queries like $near , $geoWithin , or $geoIntersects to retrieve data based on location proximity or geographical boundaries. How to Use Geospatial Index in MongoDB

Querying Data with Geospatial Index $near : Finds documents closest to a given point. $geoWithin : Finds documents within a specified geometry. $geoIntersects : Finds documents that intersect a specified geometry. Example of querying for nearby locations: places_nearby = collection . find ({ "location" : { "$near" : { "$geometry" : { "type" : "Point" , "coordinates" : [longitude, latitude] }, "$maxDistance" : 5000 # Distance in meters } } })

Efficient querying for proximity and location-based searches. Supports complex geospatial queries with GeoJSON format. Scalable and flexible for large datasets. Benefits of Using Geo-Spatial Indexing in MongoDB

This project involves building a geospatial mapping application using Flask as the backend. It retrieves geospatial data from a MongoDB database and displays it on an interactive map with Leaflet.js. This application allows users to visualize geographical data and perform tasks like proximity searches and routing. Project Overview

Flask: Web framework for Python, easy to use for building web APIs. MongoClient (from PyMongo): Python client for MongoDB to interact with the database. Flask-CORS: Handles Cross-Origin Resource Sharing (CORS) to allow requests from different domains. Leaflet.js: JavaScript library for creating interactive maps. JQuery: JavaScript library to simplify HTTP requests and DOM manipulation. Libraries and Tools Overview

Setting Up a Python Virtual Environment Create a virtual environment: python -m .venv venv Activate the virtual environment: On Windows: . venv\Scripts\activate On Mac/Linux: source .venv/bin/activate Install required libraries: pip install Flask pymongo flask-cors

Building the Flask API from flask import Flask, jsonify, make_response from pymongo import MongoClient from flask_cors import CORS app = Flask( __name__ ) CORS ( app ) client = MongoClient ( "mongodb://localhost:27017/" ) db = client [ "geo_database" ] collection = db [ "places" ] Explanation: Initializes Flask app and enables CORS. Connects to MongoDB using PyMongo and targets a database and collection.

Endpoint to retrieve nearby places based on user's current location @app.route ( '/places' , methods = [ 'GET' ]) def get_nearby_places (): # Get user's location from query parameters latitude = float (request.args.get( 'lat' )) longitude = float (request.args.get( 'lng' )) Creating API Endpoint to Fetch Places

Geospatial query to find places near the given coordinates: places = collection . find ({ "location" : { "$near" : { "$geometry" : { "type" : "Point" , "coordinates" : [longitude, latitude] }, "$maxDistance" : 5000 # Limit to 5 kilometers } } }) output = [] for place in places : output . append ({ 'name' : place [ 'name' ], 'location' : place [ 'location' ] }) return jsonify( output ) Creating API Endpoint to Fetch Places

Lightweight and Simple : Flask is a lightweight framework, perfect for small-scale applications like this. Flexible : Flask allows easy extension with additional libraries (like Flask-CORS). REST API Capabilities : Flask is well-suited for creating RESTful endpoints that can be consumed by front-end applications. Ease of Use : Minimal setup compared to more complex frameworks like Django. Why Flask for This Project?

Save the code as app.py Start the Flask server by running: python app.py Flask will run the app on http://localhost:5000 Running the Flask Server

Setting Up the Frontend with Leaflet.js < ! DOCTYPE html > < html lang = "en" > < head > < title > Geo Spatial Mapping with MongoDB and Python </ title > < link rel = "stylesheet" href = "https://unpkg.com/[email protected]/dist/leaflet.css" /> </ head > < body > < div id = "map" style = "height: 600px;" ></ div > < script src = "https://unpkg.com/[email protected]/dist/leaflet.js" ></ script > < script src = "https://code.jquery.com/jquery-3.6.0.min.js" ></ script > Explanation: Includes Leaflet.js and JQuery libraries to handle map rendering and HTTP requests. Creates a div for the map display with a height of 600px.

Leaflet.js lightweight JavaScript library Designed for interactive maps Geospatial data visualization. Benefits: User-Friendly Interactivity Integration Mapping with Leaflet.js

Fetching Data and Displaying on the Map < script > var map = L . map ( 'map' ). setView ([ , ], 2 ); L . tileLayer ( 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png' , { attribution: '© OpenStreetMap contributors' }). addTo ( map ); $ . get ( 'http://localhost:5000/places' , function ( data ) { data . forEach ( function ( place ) { var coords = place . location . coordinates ; var lat = coords [ 1 ], lng = coords [ ]; var marker = L . marker ([ lat , lng ]). addTo ( map ); marker . bindPopup ( place . name ); }); }); </ script > Explanation: Initializes Leaflet map centered at [0, 0] with zoom level 2 . Uses JQuery to fetch data from Flask API and plot locations as markers on the map.

Steps: Run a Local HTTP Server: Open your terminal. Navigate to the directory containing your index.html file. Start a Python HTTP server by running one of the following commands, depending on your Python version: For Python 3: python3 -m http.server 8000 For Python 2: python -m SimpleHTTPServer 8000 Testing the Full Application

Open Your Browser: In your browser, go to http://localhost:8000 View the map

Conclusion MongoDB supports powerful geospatial queries through GeoJSON and the 2dsphere index. Applications can efficiently filter and retrieve location-based data. Geo-spatial data is crucial for real-world applications like mapping, disaster management, and proximity-based services.