Skip to content

Instantly share code, notes, and snippets.

@ca0v
Created June 20, 2018 13:55
Show Gist options
  • Save ca0v/46411cb52eb9808376236fdf11d8cdf8 to your computer and use it in GitHub Desktop.
Save ca0v/46411cb52eb9808376236fdf11d8cdf8 to your computer and use it in GitHub Desktop.
openlayers2 geojson to geometry
import ol = require("ol2");
export type GeoJsonGeometry = {
type: "point";
coordinates: number[];
} | {
type: "multipoint";
coordinates: number[][];
} | {
type: "linestring";
coordinates: number[][];
} | {
type: "multilinestring";
coordinates: number[][][];
} | {
type: "polygon";
coordinates: number[][][];
} | {
type: "multipolygon";
coordinates: number[][][][];
};
export function fromJson(json: GeoJsonGeometry) {
switch (json.type) {
case "point":
return new ol.Geometry.Point(json.coordinates[0], json.coordinates[1]);
case "multipoint":
return new ol.Geometry.MultiPoint(json.coordinates.map(p => new ol.Geometry.Point(p[0], p[1])));
case "linestring":
return new ol.Geometry.LineString(json.coordinates.map(p => new ol.Geometry.Point(p[0], p[1])));
case "multilinestring":
return new ol.Geometry.MultiLineString(json.coordinates.map(l => new ol.Geometry.LineString(l.map(p => new ol.Geometry.Point(p[0], p[1])))));
case "polygon":
return new ol.Geometry.Polygon(json.coordinates.map(l => new ol.Geometry.LineString(l.map(p => new ol.Geometry.Point(p[0], p[1])))));
case "multipolygon":
return new ol.Geometry.MultiPolygon(json.coordinates.map(polygon => new ol.Geometry.Polygon(polygon.map(l => new ol.Geometry.LineString(l.map(p => new ol.Geometry.Point(p[0], p[1])))))));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment