Skip to content

Instantly share code, notes, and snippets.

@gearbox
Last active October 28, 2023 10:45
Show Gist options
  • Save gearbox/c4c82d959c06beb3f4eead854995e369 to your computer and use it in GitHub Desktop.
Save gearbox/c4c82d959c06beb3f4eead854995e369 to your computer and use it in GitHub Desktop.

https://stackoverflow.com/questions/4069595/flask-with-geoalchemy-sample-code

Using SQLAlchemy 0.8, Flask-SQLAlchemy and Geoalchemy 2:

from app import db
from geoalchemy2.types import Geometry


class Point(db.Model):
"""represents an x/y coordinate location."""

    __tablename__ = 'point'

    id = db.Column(db.Integer, primary_key=True)
    geom = db.Column(Geometry(geometry_type='POINT', srid=4326))

Sample query:

from geoalchemy2.elements import WKTElement
from app import models

def get_nearest(lat, lon):
    # find the nearest point to the input coordinates
    # convert the input coordinates to a WKT point and query for nearest point
    pt = WKTElement('POINT({0} {1})'.format(lon, lat), srid=4326)
    return models.Point.query.order_by(models.Point.geom.distance_box(pt)).first()

One way of converting the result to x and y coordinates (convert to GeoJSON and extract coordinates):

import geoalchemy2.functions as func
import json
from app import db

def point_geom_to_xy(pt):
    # extract x and y coordinates from a point geometry
    geom_json = json.loads(db.session.scalar(func.ST_AsGeoJSON(pt.geom)))
    return geom_json['coordinates']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment