Skip to content

Instantly share code, notes, and snippets.

@attentive
Created October 29, 2012 10:25
Show Gist options
  • Save attentive/3972823 to your computer and use it in GitHub Desktop.
Save attentive/3972823 to your computer and use it in GitHub Desktop.
PostGIS and Korma
(ns postgis
(:require [clj-json.core :as json])
(:use korma.core korma.db korma.sql.engine))
(defn intersects [first-geom second-geom]
"An extended Korma predicate that uses the PostGIS function ST_Intersects."
(sql-func "ST_Intersects" first-geom second-geom))
(defn from-wkt [wkt]
"Create a PostGIS geometry with geographic SRID from WKT using ST_GeomFromText."
(sql-func "ST_GeomFromText" wkt (int 4326)))
(defn from-geojson [geojson]
"Create a PostGIS geometry from GeoJSON using ST_GeomFromGeoJSON."
(sql-func "ST_GeomFromGeoJSON" geojson))
(defn as-geojson [pg-geom]
"Create a GeoJSON geometry from a PostGIS field, adding a CRS definition in
'short' format and restricting decimal digits to 3."
(sql-func "ST_AsGeoJSON" pg-geom (int 3) (int 2)))
(defn row->geojson-feature [geometry-field row]
"Convert a row containing a key which maps to a GeoJSON string
to an updated row containing structured data by parsing the GeoJSON."
(let [geojson (geometry-field row)
properties (dissoc row geometry-field)]
{:type "Feature",
:properties properties,
:geometry (if (= nil geojson)
nil
(json/parse-string geojson))}))
(defentity locations
(pk :short_name)
(table :locations)
(database scratch))
(defn- jsonize [rows]
(map #(row->geojson-feature :loc_geometry %1) rows))
(defn get-locations* []
(-> (select* locations)
(fields :name
:short_name
[(as-geojson :loc_geometry) :loc_geometry])))
(defn- get-intersecting-locations* [wkt]
(-> (get-locations*)
(where (intersects :loc_geometry wkt))))
(defn get-intersecting-locations [wkt]
"Find locations intersecting with the specified geometry."
(jsonize (select (get-intersecting-locations* wkt))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment