Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ca0v/9d5ac0d6814f55732349980688c21643 to your computer and use it in GitHub Desktop.
Save ca0v/9d5ac0d6814f55732349980688c21643 to your computer and use it in GitHub Desktop.
This function will convert the Well Known Text to JSON for ESRI Geometry creation. See example at http://jsfiddle.net/mac1175/6hcax/
// from https://gist.github.com/mitch-cohen/9547514
export function toJson(WKTstr: string) {
// trim leading "(" and trailing ")" characters
function unbracket(str: string) {
let left = str.indexOf("(") + 1;
let right = str.lastIndexOf(")");
if (right < str.length - 1) right = str.length;
return str.substring(left, right);
}
function convertToPoint(pt: string) {
return pt.trim().split(" ").map(parseFloat);
};
function convertToPointArray(ptArrayString: string) {
return ptArrayString.split(",").map(convertToPoint);
};
let mods = {
POINT: function (tailStr: string) {
var point = convertToPoint(unbracket(tailStr));
return {
type: 'point',
x: point[0],
y: point[1],
};
},
MULTIPOINT: function (tailStr: string) {
let points = unbracket(tailStr).split("),").map(v => unbracket(v));
return {
type: 'multipoint',
points: points.map(convertToPoint)
};
},
LINESTRING: function (tailStr: string) {
return {
type: 'linestring',
points: convertToPointArray(unbracket(tailStr))
};
},
MULTILINESTRING: function (tailStr: string) {
let pathsRaw = unbracket(tailStr).split("),").map(v => unbracket(v));
let paths = pathsRaw.map(convertToPointArray);
return {
type: 'multilinestring',
paths: paths
};
},
POLYGON: function (tailStr: string) {
return {
type: 'polygon',
rings: mods.MULTILINESTRING(tailStr).paths
};
},
MULTIPOLYGON: function (tailStr: string) {
tailStr = unbracket(tailStr);
let pathsRaw = tailStr.split("),").map(v => unbracket(v));
return {
type: 'multipolygon',
rings: pathsRaw.map(rings => mods.MULTILINESTRING(rings).paths)
};
},
};
let firstParenIndex = WKTstr.indexOf("(");
let head = WKTstr.substring(0, firstParenIndex).trim() as keyof typeof mods;
let tail = WKTstr.substr(firstParenIndex).trim();
let mod = mods[head];
return mod(tail) as {
type: "point";
x: number;
y: number;
} | {
type: "polyline";
paths: number[][][];
} | {
type: "multipoint";
points: number[][];
} | {
type: "polygon";
rings: number[][][];
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment