Skip to content

Instantly share code, notes, and snippets.

@dvhthomas
Created October 4, 2009 05:34
Show Gist options
  • Save dvhthomas/201174 to your computer and use it in GitHub Desktop.
Save dvhthomas/201174 to your computer and use it in GitHub Desktop.
Building NTS geometries from ESRI JSON
/// <summary>
/// Create valid <see cref="IGeometry"/> list from the incoming
/// JSON.
/// </summary>
/// <param name="geometryType">Only a single type of geometry is supported in each
/// query result, so the <paramref name="json"/> value is limited to one of the
/// <see cref="EsriGeometryType"/>s.</param>
/// <param name="json">JSON query result from <see cref="DownloadResource"/> which
/// is the raw JSON string.</param>
/// <returns>A list of point, polyline, polygon geometries in the same order
/// in which they are shown in the JSON input string.</returns>
public static IList<IGeometry> BuildGeometryFromJson(EsriGeometryType geometryType, string json)
{
JObject jsonObject = JObject.Parse(json);
IEnumerable<JToken> geometries = from g in jsonObject["features"].Children()
select g["geometry"];
IList<IGeometry> list;
switch (geometryType)
{
case EsriGeometryType.EsriGeometryPoint:
IList<IGeometry> points = (from p in geometries
select new Point((double) p["x"], (double) p["y"], Double.NaN))
.Cast<IGeometry>()
.ToList();
list = points;
break;
case EsriGeometryType.EsriGeometryPolygon:
throw new NotImplementedException("Polygon deserialization from JSON has not been completed yet.");
case EsriGeometryType.EsriGeometryPolyline:
IList<IGeometry> lineStrings = new List<IGeometry>();
IEnumerable<JEnumerable<JToken>> allPaths = from p in jsonObject["features"].Children()["geometry"]
select p["paths"].Children();
foreach (var eachPolylineInPath in allPaths)
{
ICoordinate[] linePoints = (from line in eachPolylineInPath.Children()
select new Coordinate((double) line[0], (double) line[1], double.NaN))
.Cast<ICoordinate>()
.ToArray();
lineStrings.Add(new LineString(linePoints));
}
list = lineStrings;
break;
default:
throw new ApplicationException(String.Format(Resources.UnsupportedGeometryType, geometryType));
}
return list;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment