Geojson raster

Geojson raster DEFAULT


'use strict';varcontours=require('d3-contour').contours;varPNG=require('pngjs').PNG;varfs=require('fs');'./rain.png'));vardata=[];for(vari=0;i<png.height;i++){for(varj=0;j<png.width;j++){data[i*png.width+j][4*(i*png.width+j)+0];}}varzValues=[8,18,36,54,72,90,108,126,144,162,180,198,216,234,252];varpolygons=contours().size([png.width,png.height]).thresholds(zValues)(data);vargeojson={type: 'FeatureCollection',features: []};for(letpolygonofpolygons){if(polygon.coordinates.length===0)continue;letcoords=convertCoords(polygon.coordinates);geojson.features.push({type: 'Feature',properties: {value: polygon.value},geometry: {type: polygon.type,coordinates: coords}})}functionconvertCoords(coords){varminLng=63.8148899733;varmaxLng=143.536486117;varmaxLat=56.3833398551;varminLat=12.7700338517;varresult=[];for(letpolyofcoords){varnewPoly=[];for(letringofpoly){if(ring.length<4)continue;varnewRing=[];for(letpofring){newRing.push([minLng+(maxLng-minLng)*(p[0]/png.width),maxLat-(maxLat-minLat)*(p[1]/png.height)]);}newPoly.push(newRing);}result.push(newPoly);}returnresult;}console.log(JSON.stringify(geojson));

Converting GeoJSON to a raster image using rasterio

Your problem stems from the fact that when you rasterize a shape, using for example, you must determine the resolution of the raster, and it must be chosen in accordance to the "size" of your feature vectors if you want your raster to retain enough information.

If you do not want to lose too many details in the rasterization process, I guess a good rule of thumb would be to set the resolution to be lower than the typical size of your individual features. For example, if your features look like squares ~1km large, a "good" resolution would be in the 10-100m range. A way to programmatically get the typical size of your features would be to compute their for example:

answered Dec 10 '19 at 14:59


18588 bronze badges

  1. The rifleman series on dvd
  2. Air force flep program
  3. Lg monitor stand screws

Understanding the Basics of Geospatial Data Using Python

The word ‘Geospatial’ indicates that data has some Geographic component to it. For us humans, it means the Earth’s surface, anywhere on the globe. It can be a city’s map, its street lines, junctions, or your address. This data comes with endless possibilities and once you get access to the Geospatial data, you can do mapping (of roads, canals, train routes, etc.), disaster management (flood / wild-fire damage estimation, etc.), and much more.

In this blog, we will introduce you to the basics of common Geospatial data formats. We will also look at some Python modules that can help you in getting started with Geospatial data.

Geospatial data primarily comes in two data formats:

Raster Data format

Represents data as a cell or a grid matrix. E.g., jpeg, GeoTiff, etc.

  • GeoTIFF: A GeoTIFF is a public domain metadata standard that has the geo-referencing information embedded within the image file

Vector Data format

Uses X & Y coordinates to represent locations. E.g., Shapefiles, GeoJSON, KLML, etc.

  • Shapefile: A shapefile is a simple, nontopological format for storing the geometric location and attribute information of geographic features
  • GeoJSON: GeoJSON is a format for encoding a variety of geographic data structures

In this blog, we will cover some basic modules to read, process and visualize the aforementioned data formats

Required modules:

  • GeoPandas
  • Contextily
  • Rasterio

Working with Vector Data Formats

GeoJSON is simply a JSON file, which conforms to the community-defined standards ( Although we can simply use JSON module to read its content, we will use GeoPandas, which supports loading of shapefiles in a similar manner:

A vector data format supports the following types of geometries:

  • Point: Represents a discrete data/location on the map. Church, Place names, etc.
  • LineString: Represents linear features. Street, Electric line, etc.
  • Polygon: Represents areas. City, Forest, etc.
  • MultiPoint, MultiLineString, MultiPolygon: List of corresponding geometry types

*You can load a shapefile (.shp file) with the same syntax, you will see a similar data frame. We will be working with Philadelphia datasets

GeoJSON Data

GeoPandas automatically extracts the Coordinate Reference System for your data and is available as the data frame attribute crs. 


Visualizing the data:


In itself, the plot might not make much sense. So let’s plot it on the World Map. For this, we will need to convert our data to EPSG:3857, Spherical Mercator projection coordinate system.


The blue lines represent the streets, the red patches represent tobacco-free zones and the green dots represent the nearest fire stations in Philadelphia.

Working with Raster Data Format

Geospatial data in raster format comes in GeoTiff files. We can use the Rasterio module to load these files in Python.


Rasterio also reads the raster properties:


A typical GeoTIFF data comes with 4 bands: Red, Green, Blue and NIR (Near-Infrared)


If you want to transform the raster more freely, you can simply convert the raster into a NumPy array with 4 channels:


What is GeoJSON and why should you care about it?


Driver short name


Driver built-in by default

This driver is built-in by default

This driver implements read/write support for access to features encoded in GeoJSON format. GeoJSON is a dialect based on the JavaScript Object Notation (JSON). JSON is a lightweight plain text format for data interchange and GeoJSON is nothing other than its specialization for geographic content.

GeoJSON is supported as an output format of a number of services: GeoServer, CartoWeb, etc.

The OGR GeoJSON driver translates GeoJSON encoded data to objects of the OGR Simple Features model: Datasource, Layer, Feature, Geometry. The implementation is based on GeoJSON Specification, v1.0.

Starting with GDAL 2.1.0, the GeoJSON driver supports updating existing GeoJSON files. In that case, the default value for the NATIVE_DATA open option will be YES.


The OGR GeoJSON driver accepts three types of sources of data:

  • Uniform Resource Locator (URL) - a Web address to perform HTTP request

  • Plain text file with GeoJSON data - identified from the file extension .geojson or .json

  • Text passed directly and encoded in GeoJSON

Starting with GDAL 2.3, the URL/filename/text might be prefixed with GeoJSON: to avoid any ambiguity with other drivers.


A GeoJSON datasource is translated to single OGRLayer object with pre-defined name OGRGeoJSON:


It is also valid to assume that OGRDataSource::GetLayerCount() for GeoJSON datasource always returns 1.

Starting with GDAL 2.2, the layer name is built with the following logic:

  1. If a “name” member is found at the FeatureCollection level, it is used.

  2. Otherwise if the filename is regular (ie not a URL with query parameters), then the filename without extension and path is used as the layer name.

  3. Otherwise OGRGeoJSON is used.

Accessing Web Service as a datasource (i.e. FeatureServer), each request will produce new layer. This behavior conforms to stateless nature of HTTP transaction and is similar to how Web browsers operate: single request == single page.

If a top-level member of GeoJSON data is of any other type than FeatureCollection, the driver will produce a layer with only one feature. Otherwise, a layer will consists of a set of features.

If the NATIVE_DATA open option is set to YES, members at the level of the FeatureCollection will be stored as a serialized JSon object in the NATIVE_DATA item of the NATIVE_DATA metadata domain of the layer object (and “application/vnd.geo+json” in the NATIVE_MEDIA_TYPE of the NATIVE_DATA metadata domain).


The OGR GeoJSON driver maps each object of following types to new OGRFeature object: Point, LineString, Polygon, GeometryCollection, Feature.

According to the GeoJSON Specification, only the Feature object must have a member with name properties. Each and every member of properties is translated to OGR object of type of OGRField and added to corresponding OGRFeature object.

The GeoJSON Specification does not require all Feature objects in a collection to have the same schema of properties. If Feature objects in a set defined by FeatureCollection object have different schema of properties, then resulting schema of fields in OGRFeatureDefn is generated as union of all Feature properties.

Schema detection will recognized fields of type String, Integer, Real, StringList, IntegerList and RealList, Integer(Boolean), Date, Time and DateTime.

It is possible to tell the driver to not to process attributes by setting environment variable ATTRIBUTES_SKIP=YES. Default behavior is to preserve all attributes (as an union, see previous paragraph), what is equal to setting ATTRIBUTES_SKIP=NO.

If the NATIVE_DATA open option is set to YES, the Feature JSon object will be stored as a serialized JSon object in the NativeData property of the OGRFeature object (and “application/vnd.geo+json” in the NativeMediaType property). On write, if a OGRFeature to be written has its NativeMediaType property set to “application/vnd.geo+json” and its NativeData property set to a string that is a serialized JSon object, then extra members of this object (i.e. not the “property” dictionary, nor the first 3 dimensions of geometry coordinates) will be used to enhance the created JSon object from the OGRFeature. See RFC 60 : Improved round-tripping in OGR for more details.


Similarly to the issue with mixed-properties features, the GeoJSON Specification draft does not require all Feature objects in a collection must have geometry of the same type. Fortunately, OGR objects model does allow to have geometries of different types in single layer - a heterogeneous layer. By default, the GeoJSON driver preserves type of geometries.

However, sometimes there is a need to generate a homogeneous layer from a set of heterogeneous features. For this purpose, it is possible to tell the driver to wrap all geometries with OGRGeometryCollection type as a common denominator. This behavior may be controlled by setting the configuration option to YES (default is NO).

configuration options

  • - used to control translation of geometries: YES - wrap geometries with OGRGeometryCollection type

  • - controls translation of attributes: YES - skip all attributes

  • - (GDAL >= 3.0.2) size in MBytes of the maximum accepted single feature, default value is 200MB

Open options

  • FLATTEN_NESTED_ATTRIBUTES = YES/NO: Whether to recursively explore nested objects and produce flatten OGR attributes. Defaults to NO.

  • NESTED_ATTRIBUTE_SEPARATOR = character: Separator between components of nested attributes. Defaults to ‘_’

  • FEATURE_SERVER_PAGING = YES/NO: Whether to automatically scroll through results with a ArcGIS Feature Service endpoint.

  • NATIVE_DATA = YES/NO: (GDAL >= 2.1) Whether to store the native JSon representation at FeatureCollection and Feature level. Defaults to NO. This option can be used to improve round-tripping from GeoJSON to GeoJSON by preserving some extra JSon objects that would otherwise be ignored by the OGR abstraction. Note that ogr2ogr by default enable this option, unless you specify its -noNativeData switch.

  • ARRAY_AS_STRING = YES/NO: (GDAL >= 2.1) Whether to expose JSon arrays of strings, integers or reals as a OGR String. Default is NO. Can also be set with the configuration option.

  • DATE_AS_STRING = YES/NO: (GDAL >= 3.0.3) Whether to expose date/time/date-time content using dedicated OGR date/time/date-time types or as a OGR String. Default is NO (that is date/time/date-time are detected as such). Can also be set with the configuration option.

To explain FLATTEN_NESTED_ATTRIBUTES, consider the following GeoJSON fragment:


“ogrinfo test.json -al -oo FLATTEN_NESTED_ATTRIBUTES=yes” reports:


Layer creation options

  • WRITE_BBOX = YES/NO: Set to YES to write a bbox property with the bounding box of the geometries at the feature and feature collection level. Defaults to NO.

  • COORDINATE_PRECISION = int_number: Maximum number of figures after decimal separator to write in coordinates. Default to 15 for GeoJSON 2008, and 7 for RFC 7946. “Smart” truncation will occur to remove trailing zeros.

  • SIGNIFICANT_FIGURES = int_number: (OGR >= 2.1) Maximum number of significant figures when writing floating-point numbers. Default to 17. If explicitly specified, and COORDINATE_PRECISION is not, this will also apply to coordinates.

  • NATIVE_DATA=string. (OGR >= 2.1) Serialized JSon object that contains extra properties to store at FeatureCollection level.

  • NATIVE_MEDIA_TYPE=string. (OGR >= 2.1) Format of NATIVE_DATA. Must be “application/vnd.geo+json”, otherwise NATIVE_DATA will be ignored.

  • RFC7946=YES/NO. (OGR >= 2.2) Whether to use RFC 7946 standard. Otherwise GeoJSON 2008 initial version will be used. Default is NO (thus GeoJSON 2008)

  • WRITE_NAME=YES/NO. (OGR >= 2.2) Whether to write a “name” property at feature collection level with layer name. Defaults to YES.

  • DESCRIPTION=string. (OGR >= 2.2) (Long) description to write in a “description” property at feature collection level. On reading, this will be reported in the DESCRIPTION metadata item of the layer.

  • ID_FIELD=string. (OGR >= 2.3) Name of the source field that must be written as the ‘id’ member of Feature objects.

  • ID_TYPE=AUTO/String/Integer. (OGR >= 2.3) Type of the ‘id’ member of Feature objects.

  • ID_GENERATE=YES/NO. (OGR >= 3.1) Auto-generate feature ids

  • WRITE_NON_FINITE_VALUES=YES/NO. (OGR >= 2.4) Whether to write NaN / Infinity values. Such values are not allowed in strict JSon mode, but some JSon parsers (libjson-c >= 0.12 for exampl) can understand them as they are allowed by ECMAScript. Defaults to NO

VSI Virtual File System API support

The driver supports reading and writing to files managed by VSI Virtual File System API, which includes “regular” files, as well as files in the /vsizip/ (read-write), /vsigzip/ (read-write), /vsicurl/ (read-only) domains.

Writing to /dev/stdout or /vsistdout/ is also supported.

RFC 7946 write support

By default, the driver will write GeoJSON files following GeoJSON 2008 specification. When specifying the RFC7946=YES creation option, the RFC 7946 standard will be used instead.

The differences between the 2 versions are mentioned in Appendix B of RFC 7946 and recalled here for what matters to the driver:

  • Coordinates must be geographic over the WGS 84 ellipsoid, hence if the spatial reference system specified at layer creation time is not EPSG:4326, on-the-fly reprojection will be done by the driver.

  • Polygons will be written such as to follow the right-hand rule for orientation (counterclockwise external rings, clockwise internal rings).

  • The values of a “bbox” array are “[west, south, east, north]”, not “[minx, miny, maxx, maxy]”

  • Some extension member names (see previous section about round/tripping) are forbidden in the FeatureCollection, Feature and Geometry objects.

  • The default coordinate precision is 7 decimal digits after decimal separator.


How to dump content of .geojson file:


How to query features from remote service with filtering by attribute:


How to translate number of features queried from FeatureServer to ESRI Shapefile:

ogr2ogr-f"ESRI Shapefile"cities.shphttp://featureserver/cities/.geojsonOGRGeoJSON

How to translate a ESRI Shapefile into a RFC 7946 GeoJSON file:



Raster geojson


JSON subset for geospatial data

GeoJSON[1] is an open standard format designed for representing simple geographical features, along with their non-spatial attributes. It is based on the JSON format.

The features include points (therefore addresses and locations), line strings (therefore streets, highways and boundaries), polygons (countries, provinces, tracts of land), and multi-part collections of these types. GeoJSON features need not represent entities of the physical world only; mobile routing and navigation apps, for example, might describe their service coverage using GeoJSON.[2]

The GeoJSON format differs from other GIS standards in that it was written and is maintained not by a formal standards organization, but by an Internet working group of developers.[3]

A notable offspring of GeoJSON is TopoJSON, an extension of GeoJSON that encodes geospatial topology and that typically provides smaller file sizes.


The GeoJSON format working group and discussion were begun in March 2007[4] and the format specification was finalized in June 2008.

In April 2015 the Internet Engineering Task Force has founded the Geographic JSON working group[5] which released GeoJSON as RFC 7946 in August 2016.




Points are [x, y] or [x, y, z]. They may be [longitude, latitude ] or [eastings, northings]. Elevation is an optional third number. They are decimal numbers. [6]

For example, London (51.5074° North, 0.1278° West) is [-0.1278, 51.5074]

Type Examples
PointSFA Point.svg
LineStringSFA LineString.svg
PolygonSFA Polygon.svg
SFA Polygon with hole.svg
Type Examples
MultiPointSFA MultiPoint.svg
MultiLineStringSFA MultiLineString.svg
MultiPolygonSFA MultiPolygon.svg
SFA MultiPolygon with hole.svg
GeometryCollection SFA GeometryCollection.svg


TopoJSON is an extension of GeoJSON that encodes topology. Rather than representing geometries discretely, geometries in TopoJSON files are stitched together from shared line segments called arcs.[7]Arcs are sequences of points, while line strings and polygons are defined as sequences of arcs. Each arc is defined only once, but can be referenced several times by different shapes, thus reducing redundancy and decreasing the file size.[8] In addition, TopoJSON facilitates applications that use topology, such as topology-preserving shape simplification, automatic map coloring, and cartograms.

A reference implementation of the TopoJSON specification is available as a command-line tool to encode TopoJSON from GeoJSON (or ESRI Shapefiles) and a client sideJavaScript library to decode TopoJSON back to GeoJSON again. TopoJSON is also supported by the popular OGR tool as of version 1.11[9] and PostGIS as of version 2.1.0.[10]

TopoJSON Schema[edit]

Given a GIS shape near coordinateslatitude 0° and longitude 0°, a simple but valid and complete topojson file containing all metadata, Polygon, LineString, Point elements, arcs and properties is defined as follows:


See also[edit]



External links[edit]


Convert a raster to GeoJSON polygons in PostGIS

If you look at the example on the man page for ST_PixelAsPolygons you will see how you can access the geometries using syntax (similar in spirit to how ST_Dump works to turn a set or records into individual rows). Following on from that example, you can pass to the ST_AsGeoJSON function, eg,

which will return the three rows:




If you wish to turn this into a FeatureCollection, you can use a combination of row_to_json, array_agg and array_to_json to group the rows together into an array and add in the "type":"FeatureCollection" before the features array. The general idea is that you select the 'Feature', the GeoJSON representation of the geometry and the properties in one subquery, and then use array_to_json and array_agg to group this into an array of features, with 'FeatureCollection' as type before the array. Finally, you select row_to_json to group this all together inside {}.

Note you have to do the nasty subselect on the properties -- in your case the raster pixel values -- to avoid the labels being f1, f2, etc. See this Postgres Online article for more information.

which now produces:

Note: You need to cast the ST_AsGeoJSON to JSON, with the :: operator, or else you will end up with all the quotes being escaped, as \" in the output.


Now discussing:


1257 1258 1259 1260 1261