Flask with GeoAlchemy sample code


Can anyone provide any sample code for Flask with GeoAlchemy?

12/1/2014 3:22:46 AM

Accepted Answer

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']
4/19/2013 12:32:10 AM

You can use it with Flask-SQLAlchemy, but you can use it with plain SQLAlchemy too. Just translate the sample models from GeoAlchemy to Flask-SQLAlchemy. Something like this:

class Spot(db.Model):
    __tablename__ = 'spots'
    id = db.Column(Integer, primary_key=True)
    name = db.Column(Unicode, nullable=False)
    height = db.Column(Integer)
    created = db.Column(DateTime, default=datetime.now())
    geom = db.GeometryColumn(Point(2))

I've not tested the code, but it should be a fair transcription.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow