2010-11-01 60 views

回答

15

使用SQLAlchemy的0.8,瓶-SQLAlchemy的和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)) 

示例查詢:

計算結果轉換爲x和y座標的
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() 

一種方式(轉換爲以GeoJSON並提取座標):

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'] 
1

如果您不僅限於使用Flask,您可能需要嘗試使用MapFish,這是基於Pylons並使用GeoAlchemy。

1

您可以將它與Flask-SQLAlchemy一起使用,但您也可以將它與純SQLAlchemy一起使用。只需將sample models from GeoAlchemy翻譯爲Flask-SQLAlchemy即可。類似這樣的:

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)) 

我沒有測試代碼,但它應該是一個公平的轉錄。

+2

此代碼不起作用:它會給你'AttributeError:'SQLAlchemy'對象沒有屬性'GeometryColumn'' – jsalonen 2012-04-01 21:05:41

0
from myapp import db 
from geoalchemy import GeometryColumn, Point 

class FixXX(db.Model): 

    __tablename__ = 'fixXX' 

    fix_pk = db.Column(db.Integer, primary_key=True) 
    fix = db.Column(db.String) 
    geometry = GeometryColumn(Point(2, srid=4326)) 

GeometryDDL(FixXX.__table__)