GeoJSON
editGeoJSON is the JSON format of web maps. GeoJson.Read and GeoJson.Parse read a FeatureCollection, a Feature or a geometry, and GeoJson.Write and GeoJson.Format write a FeatureCollection:
GeoFeatureCollection countries;
using (var stream = File.OpenRead("countries.geojson"))
{
countries = GeoJson.Read(stream);
}
// A JSON number is a double, and a string is a string
var large = countries.Where(country => (double)country.Properties["population"]! > 50).ToList();
Assert.Equal("France", Assert.Single(large).Properties["name"]);
using (var stream = File.Create("large-countries.geojson"))
{
GeoJson.Write(new GeoFeatureCollection(large), stream, new GeoJsonWriterOptions { Indented = true });
}ParseGeometry and FormatGeometry read and write a single geometry.
Read a large document
GeoJson.ReadFeaturesAsync returns the features one at a time, as it reads the stream: only the feature being read is in memory, so an export of millions of features can be filtered or converted with bounded memory:
// The features are read one at a time: a large export is processed without loading it in memory
await using var stream = File.OpenRead(path);
var points = 0;
await foreach (var feature in GeoJson.ReadFeaturesAsync(stream))
{
if (feature.Geometry is GeoPoint)
{
points++;
}
}
Assert.Equal(1, points);- The members of the
FeatureCollectioncan be in any order. The features are returned as soon as thefeaturesarray starts, and atypewritten after the array that is notFeatureCollectionthrows aFormatExceptiononce they are returned. - The
nameof the collection is not returned: use Read to get it. - A
Featureor a geometry is a single feature: it is read whole. - Invalid data throws a
FormatExceptionwhen the reader reaches it: the features before it are returned first.
What the reader keeps
- The seven geometry types, with their altitudes.
- The
nameof aFeatureCollection, as Name. Thebboxand the other members that GeoJSON does not define are ignored. - The properties: a JSON string is a
string, a number adouble,trueandfalseabool,nullisnull, and an object or an array is aJsonElement. - The
id: a string, or the JSON text of a number (42).
Options of the writer
GeoJsonWriterOptions sets:
- Indented: indent the JSON.
- WriteBoundingBoxes: add a
bboxto the collection, the features and the geometries.
The writer writes the identifiers as strings, the numbers as JSON numbers (null when they are not finite), a JsonElement as it is, a dictionary as an object, a collection as an array, and the other values, such as dates, as their text. Only the characters JSON requires are escaped, so names in other scripts stay readable.