1

I am converting osm xml to GeoJSON using ogr2ogr and I want to use the osm_id, nested under properties, as a top level id field.

Running

ogr2ogr -f GeoJSON output.geojson input.osm points

produces something like the following, where the osm_id is nested within the properties:

{
  "type": "FeatureCollection",
  "name": "points",
  "crs": {
    "type": "name",
    "properties": {
      "name": "urn:ogc:def:crs:OGC:1.3:CRS84"
    }
  },
  "features": [
{
      "type": "Feature",
      "properties": {
        "osm_id": "32927591",
        "other_tags": "\"noref\"=>\"yes\"",
        "highway": "motorway_junction"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [
          -122.4254065,
          37.7313829
        ]
      }
    }
  ]
}

But I would like to generate a the Geojson using the osm_id as a top level id attribute:

  "features": [
{
      "type": "Feature",
      "id": "32927591",
      "properties": {
        "osm_id": "32927591",
        "other_tags": "\"noref\"=>\"yes\"",
        "highway": "motorway_junction"
      },
      "geometry": {...

Is there a way to do this with ogr2ogr? Is there a different tool you'd recommend?

  • Solution, for my version of GDAL, was to use the preserve_fid flag – andrew Jun 19 '18 at 18:56
2

In your case osm_id is a fid field already in the source data and you can simply run ogr2ogr with the -preserve_fid option http://www.gdal.org/ogr2ogr.html.

With GDAL version 2.3 or higher it is also possible to select the field that will be used as id in GeoJSON by using the GeoJSON driver specific layer creation option -lco id_field= http://www.gdal.org/drv_geojson.html. Just take care to select a field that is unique in the source data because duplicate fids will make trouble later.

Your command with the latter approach would be

ogr2ogr -f GeoJSON -lco id_field=osm_id output.geojson input.osm points

Test with a small self-made dataset:

ogr2ogr -f geojson -lco id_field=osm_id osm_id_test.json osm_id_test.jml

Result:

{
"type": "FeatureCollection",
"name": "osm_id_test",
"features": [
{ "type": "Feature", "id": 1, "properties": { }, "geometry": { "type": "Point", "coordinates": [ 383.0, 458.0 ] } },
{ "type": "Feature", "id": 2, "properties": { }, "geometry": { "type": "Point", "coordinates": [ 440.0, 381.0 ] } }
]
}
  • Unfortunately I have 2.2.4. But I just figured out that I can use the preserve_fid flag to achieve the desired outcome. – andrew Jun 19 '18 at 18:55
  • I edited my answer so that -preserve_fid is the primary option and id_field an alternative for that. – user30184 Jun 19 '18 at 19:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.