Skip to content

Instantly share code, notes, and snippets.

@iamhatesz
Created December 11, 2016 21:14
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iamhatesz/4f4b83fd32c52f002766f9a70c2f6a71 to your computer and use it in GitHub Desktop.
Save iamhatesz/4f4b83fd32c52f002766f9a70c2f6a71 to your computer and use it in GitHub Desktop.
import io.circe._
import io.circe.generic.auto._
import io.circe.parser._
val jsonPoint = "{ \"type\": \"Point\", \"coordinates\": [100.0, 0.0] }"
val jsonLineString = "{ \"type\": \"LineString\",\n \"coordinates\": [ [100.0, 0.0], [101.0, 1.0] ]\n }"
val jsonPolygon = "{ \"type\": \"Polygon\",\n \"coordinates\": [\n [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ]\n ]\n }"
val jsonPolygonWithHoles = "{ \"type\": \"Polygon\",\n \"coordinates\": [\n [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ],\n [ [100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2] ]\n ]\n }"
val jsonGC = "{ \"type\": \"GeometryCollection\",\n \"geometries\": [\n { \"type\": \"Point\",\n \"coordinates\": [100.0, 0.0]\n },\n { \"type\": \"LineString\",\n \"coordinates\": [ [101.0, 0.0], [102.0, 1.0] ]\n }\n ]\n }"
case class Coordinates(x: Double, y: Double)
object Coordinates {
implicit val decoder: Decoder[Coordinates] =
Decoder[(Double, Double)].map(p => Coordinates(p._1, p._2))
}
sealed trait Geometry
case class Point(coordinates: Coordinates) extends Geometry
case class LineString(coordinates: List[Coordinates]) extends Geometry
case class MultiPoint(coordinates: List[Coordinates]) extends Geometry
case class MultiLineString(coordinates: List[List[Coordinates]]) extends Geometry
case class Polygon(coordinates: List[List[Coordinates]]) extends Geometry
case class MultiPolygon(coordinates: List[List[List[Coordinates]]]) extends Geometry
case class GeometryCollection(geometries: List[Geometry]) extends Geometry
object Geometry {
implicit val decoder: Decoder[Geometry] = Decoder.instance { c =>
c.downField("type").as[String].map(_.toLowerCase).flatMap {
case "point" => c.as[Point]
case "linestring" => c.as[LineString]
case "multipoint" => c.as[MultiPoint]
case "multilinestring" => c.as[MultiLineString]
case "polygon" => c.as[Polygon]
case "multipolygon" => c.as[MultiPolygon]
case "geometrycollection" => c.as[GeometryCollection]
}
}
}
decode[Geometry](jsonPoint)
decode[Geometry](jsonLineString)
decode[Geometry](jsonPolygon)
decode[Geometry](jsonPolygonWithHoles)
decode[Geometry](jsonGC)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment