Code Monkey home page Code Monkey logo

osmtogeojson's Introduction

osmtogeojson

Converts OSM data to GeoJSON. Try the demo!

This code is used in and maintained by the overpass turbo project.

Build Status

Usage

command line tool

Installation:

  $ npm install -g osmtogeojson

Usage:

$ osmtogeojson file.osm > file.geojson

Supported command line options are shown with:

$ osmtogeojson --help

When working with extra large data files (≳ 100 MB) it is recommended to run the programm with a little extra memory to avoid process out of memory errors. The easiest way to do this is by running the command as node <path-to-osmtogeojson> and setting the --max_old_space_size=… parameter to the available memory size in MB (osmtogeojson typically needs about 4-5 times the input data size). On a Unix system, you can use the following command:

$ node --max_old_space_size=8192 `which osmtogeojson` large.osm > large.geojson

nodejs library

Installation:

$ npm install osmtogeojson

Usage:

var osmtogeojson = require('osmtogeojson');
osmtogeojson(osm_data);

browser library

<script src='osmtogeojson.js'></script>

osmtogeojson(osm_data);

API

osmtogeojson( data, options )

Converts OSM data into GeoJSON.

  • data: the OSM data. Either as a XML DOM or in OSM JSON.
  • options: optional. The following options can be used:
    • flatProperties: If true, the resulting GeoJSON feature's properties will be a simple key-value list instead of a structured json object (with separate tags and metadata). default: false
    • uninterestingTags: Either a blacklist of tag keys or a callback function. Will be used to decide if a feature is interesting enough for its own GeoJSON feature.
    • polygonFeatures: Either a json object or callback function that is used to determine if a closed way should be treated as a Polygon or LineString. read more

The result is a javascript object of GeoJSON data:

GeoJSON

The GeoJSON produced by this library will include exactly one GeoJSON-feature for each of the following OSM objects (that is everything that is also visible in overpass turbo's map view):

  • all unconnected or interesting tagged nodes (POIs)
  • all ways (except uninteresting multipolygon outlines)
  • all multipolygons (simple multipolygons with exactly one closed outer way are present via their outer way)

All data is given as a FeatureCollection. Each Feature in the collection has an id property that is formed from the type and id of the original OSM object (e.g. node/123) and has the member properties containing the following data:

  • type: the OSM data type
  • id: the OSM id
  • tags: a collection of all tags
  • meta: metainformaton about the feature (e.g. version, timestamp, user, etc.)
  • relations: an array of relations the feature is member of. Each relation is encoded as an object literal containing the following properties: role (membership role), rel (the relation's id) and reltags (contains all tags of the relation)
  • tainted: this flag is set when the feature's geometry is incomplete (e.g. missing nodes of a way or missing ways of a multipolygon)

If the option flatProperties is set to true, the properties object will not contain any nested object literals, but directly provide a concise id, meta data and the tags of the respective OSM object.

osmtogeojson's People

Contributors

danieldegroot2 avatar enko avatar matkoniecz avatar neiljp avatar olicarbo avatar russellporter avatar tyrasd avatar vavsab avatar vsivsi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

osmtogeojson's Issues

uninterestingTags not working

My function looks like this, parsing data coming straight from the overpass api

geojson = osmtogeojson(JSON.parse(body), {
    flatProperties: true,
    uninterestingTags: {
        "highway": true,
        "maxspeed": true,
        "ref": true,
        "not:name": true,
        "not:name:note": true,
        "source": true,
        "alt_name": true,
        "note": true,
        "oneway": true
    }
});

The flatProperties seems to work but the tags listed there aren't stripped out, here is a sample from the output. Note highway and maxpseed are still present.

{
    "type": "Feature",
    "id": "way/5119284",
    "properties": {
        "highway": "residential",
        "maxspeed": "20 mph",
        "name": "St Pauls Road",
        "id": "way/5119284"
    },
    "geometry": {
        "type": "LineString",
        "coordinates": [
            [-1.0945502, 50.7943406],
            [-1.0947346, 50.7936904],
            [-1.0949974, 50.792788],
            [-1.0949348, 50.7926471],
            [-1.0945846, 50.7918164],
            [-1.0943593, 50.7914569],
            [-1.0944788, 50.7911133]
        ]
    }
}

Am I missing something? My goal is to try reduce the size of the geojson I am sending to the browser.

error not a package

 > sudo npm install -g osmtogeojson
npm ERR! not a package /......../osmtogeojson/osmtogeojson
npm ERR! addLocal Could not install /...../osmtogeojson/osmtogeojson
npm ERR! FreeBSD 10.2-RELEASE
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "-g" "osmtogeojson"
npm ERR! node v4.1.1
npm ERR! npm  v2.14.4
npm ERR! path /tmp/npm-97941-291b1eb9/unpack-5be1b0b108ce/package.json
npm ERR! code ENOENT
npm ERR! errno -2
npm ERR! syscall open

npm ERR! enoent ENOENT: no such file or directory, open '/tmp/npm-97941-291b1eb9/unpack-5be1b0b108ce/package.json'
npm ERR! enoent This is most likely not a problem with npm itself
npm ERR! enoent and is related to npm not being able to find a file.
npm ERR! enoent 

npm ERR! Please include the following file with any support request:
npm ERR!     /...../osmtogeojson/npm-debug.log
0 info it worked if it ends with ok
1 verbose cli [ '/usr/local/bin/node',
1 verbose cli   '/usr/local/bin/npm',
1 verbose cli   'install',
1 verbose cli   '-g',
1 verbose cli   'osmtogeojson' ]
2 info using [email protected]
3 info using [email protected]
4 verbose install initial load of /usr/local/lib/package.json
5 verbose readDependencies loading dependencies from /usr/local/lib/package.json
6 silly cache add args [ 'osmtogeojson', null ]
7 verbose cache add spec osmtogeojson
8 silly cache add parsed spec Result {
8 silly cache add   raw: 'osmtogeojson',
8 silly cache add   scope: null,
8 silly cache add   name: null,
8 silly cache add   rawSpec: 'osmtogeojson',
8 silly cache add   spec: '/........./osmtogeojson/osmtogeojson',
8 silly cache add   type: 'local' }
9 silly addLocalTarball shasum (computed) 698d2a5121ab0164244446bccce4546d36197e1e
10 verbose addTmpTarball /......../osmtogeojson/osmtogeojson not in flight; adding
11 verbose addTmpTarball validating metadata from /......../osmtogeojson/osmtogeojson
12 verbose tar unpack /...../osmtogeojson/osmtogeojson
13 verbose tar unpacking to /tmp/npm-97941-291b1eb9/unpack-5be1b0b108ce
14 silly gentlyRm /tmp/npm-97941-291b1eb9/unpack-5be1b0b108ce is being purged
15 verbose gentlyRm don't care about contents; nuking /tmp/npm-97941-291b1eb9/unpack-5be1b0b108ce
16 silly gunzTarPerm modes [ '755', '644' ]
17 error not a package /...../osmtogeojson/osmtogeojson
18 error addLocal Could not install /...../osmtogeojson/osmtogeojson
19 verbose stack Error: ENOENT: no such file or directory, open '/tmp/npm-97941-291b1eb9/unpack-5be1b0b108ce/package.json'
19 verbose stack     at Error (native)
20 verbose cwd /....../osmtogeojson
21 error FreeBSD 10.2-RELEASE
22 error argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "-g" "osmtogeojson"
23 error node v4.1.1
24 error npm  v2.14.4
25 error path /tmp/npm-97941-291b1eb9/unpack-5be1b0b108ce/package.json
26 error code ENOENT
27 error errno -2
28 error syscall open
29 error enoent ENOENT: no such file or directory, open '/tmp/npm-97941-291b1eb9/unpack-5be1b0b108ce/package.json'
29 error enoent This is most likely not a problem with npm itself
29 error enoent and is related to npm not being able to find a file.
30 verbose exit [ -2, true ]

handle non-matching inner and outer rings in simple multipolygons

See

osmtogeojson/test/osm.test.js

Lines 1271 to 1350 in af518f0

// simple multipolygon
json = {
elements: [
{
type: "relation",
tags: {"type": "multipolygon"},
id: 1,
members: [
{
type: "way",
ref: 2,
role: "outer"
},
{
type: "way",
ref: 3,
role: "inner"
}
]
},
{
type: "way",
id: 2,
nodes: [4,5,6,7,4]
},
{
type: "node",
id: 4,
lat: 0.0,
lon: 0.0
},
{
type: "node",
id: 5,
lat: 1.0,
lon: 0.0
},
{
type: "node",
id: 6,
lat: 1.0,
lon: 1.0
},
{
type: "node",
id: 7,
lat: 0.0,
lon: 1.0
},
{
type: "way",
id: 3,
nodes: [8,9,10,8]
},
{
type: "node",
id: 8,
lat: 3.0,
lon: 3.0
},
{
type: "node",
id: 9,
lat: 4.0,
lon: 3.0
},
{
type: "node",
id: 10,
lat: 3.0,
lon: 4.0
}
]
};
result = osmtogeojson.toGeojson(json);
expect(result.features).to.have.length(1);
expect(result.features[0].properties.id).to.equal(2);
expect(result.features[0].geometry.type).to.equal("Polygon");
expect(result.features[0].geometry.coordinates).to.have.length(1);
expect(result.features[0].geometry.coordinates[0]).to.have.length(1);

polygonFeatures parsing roads as type Polygon not LineString

When I use overpass turbo and export roads around my position as geojson I get every geometry.type as LineString.

However when I use this library and call the overpass API myself and convert I get them as Polygon

I'm using

geojson = osmtogeojson(JSON.parse(body), {
    "polygonFeatures": settings.polygonFeatures
});

where settings.polygonFeatures is the same as https://github.com/tyrasd/osmtogeojson/blob/gh-pages/polygon_features.json which is what overpass turbo uses according to https://wiki.openstreetmap.org/wiki/Overpass_turbo/Polygon_Features

What have I missed?

3.0 documentation

  • list of breaking changes incl. how to upgrade
  • deduplication callback #23
  • pbf parsing (see #61)

add parameter to whitelist keys

Hi there,
as complex Overpass requests resulting in a huge amount of features may have a big common feature type, it would be nice to whitelist keys during the conversion to GeoJSON.
Equivalent to the uninterestingTags parameter, there could be an interestingTags parameter which provides a list of allowed keys to the converter.
What do you think about that?

List way membership of points

Hello,
I think it could be interesting to keep track of the nodes identifiers in OSM way-based features, for example by adding an array of nodes ID in feature properties. This would allow some advanced processing (like finding a door direction along a wall). Do you think it can be implemented ?

Error when processing big files (RangeError: Invalid typed array length)

Hi,
I am trying to convert a big OSM file (shapes for France ~ 3 GB) to GeoJSON.

# node --max_old_space_size=100000 ../node_modules/osmtogeojson/osmtogeojson "boundaries/france-latest.osm.pbf" > "geojson/france-latest.osm.pbf.geojson"

However, I get the following error:

buffer.js:68
   const ui8 = new Uint8Array(size);
               ^

RangeError: Invalid typed array length
   at new Uint8Array (native)
   at createBuffer (buffer.js:68:17)
   at allocate (buffer.js:216:12)
   at Function.Buffer.allocUnsafe (buffer.js:176:10)
   at Function.Buffer.concat (buffer.js:354:23)
   at Object.module.exports [as join]
(/srv/sms/osm-rdf/node_modules/bops/join.js:6:12)
   at ConcatStream.getBody
(/srv/sms/osm-rdf/node_modules/concat-stream/index.js:37:42)
   at ConcatStream.end
(/srv/sms/osm-rdf/node_modules/concat-stream/index.js:42:29)
   at ReadStream.onend (_stream_readable.js:517:10)
   at ReadStream.g (events.js:286:16)

It works pretty well for my other shapefiles which have a size up to 2 GB. But this one gives me the error.
Do you have any idea how to fix it?

NuGet support

Is it possible to upload this library to NuGet as well?

Out of memory crash on procesing 141 MB osm file (32 bit Win7, run from command line)

Is it expected that osmtogeojson will be processing this file for three hours and then crash with "FATAL ERROR: CALL_AND_RETRY_2 Allocation failed - process out of memory"? What is the maximal size of file safe to be processed?

I aquired the file from overpass API by visiting following URL (note that entire following line is an URL):

http://overpass-api.de/api/interpreter?data=(node(50,19.78,50.11,20.09);<;);out meta;

File processed with osmfilter, filtered to 28 MB is happily processed within 30 seconds.

too large osm xml file ending in an error

When the file is too large, we got this error:

buffer.js:243
this.parent = new SlowBuffer(this.length);
^
RangeError: length > kMaxLength
at new Buffer (buffer.js:243:21)
at Function.Buffer.concat (buffer.js:501:16)
at Object.module.exports [as join](C:UsersMPHAppDataRoamingnpmnode_mo
dulesosmtogeojsonnode_modulesconcat-streamnode_modulesbopsjoin.js:6:12)
at ConcatStream.getBody (C:\Users\MPH\AppData\Roaming\npm\node_modules\osmto
geojson\node_modules\concat-stream\index.js:37:42)
at ConcatStream.end (C:\Users\MPH\AppData\Roaming\npm\node_modules\osmtogeoj
son\node_modules\concat-stream\index.js:42:29)
at onend (stream.js:66:10)
at EventEmitter.emit (events.js:126:20)
at afterRead (fs.js:1330:12)
at Object.wrapper as oncomplete

How to deal with this issue when it is not possible to split the file?

Relations with members are not included if a member is one of the features in the OSM source file

Here's a gist with a minimal test case: https://gist.github.com/mnquintana/2d7009ea406b6377269a?short_path=87290a1

  1. I have a relation with two members, each of which is a way
  2. OSM export includes both members and the relation that contains them

Expected

After parsing with osmtogeojson, there will be 3 features - two ways, and a relation.

Actual

After parsing with osmtogeojson (for the purposes of this example, done via overpass-turbo), there are only two features, each of which is associated with the relation, but the relation is not included as a feature.

Only send selected geojson elements in leaflet

The following link provides my code that gets all OSM alley elements in a map and that has a button to print all elements retrieved with overpass api.

https://stackoverflow.com/questions/30833825/send-only-selected-geojson-elements-in-leaflet

Instead retrieving all elements, I would like to me able to :

  1. select multiple elements on my map (the selected elements would be marked with a different color then blue) by clicking on those I want.
  2. print only the selected elements.

Any idea how to do this?

I hope this is ok to create an issue for a question...

Thanks so much!!

better documentation

documentation of:

  • produced GeoJSON structure
  • conversion internals (polygon detection, multipolygons, ignored tags)
  • API parameters, options (#4)

[email protected] — coords is not defined

_convert2geoJSON @ index.js:782
_overpassJSON2geoJSON @ index.js:188
osmtogeojson @ index.js:44

Default npm install and I was processing overpass result set.
Webpack packaging. Browser Error. Ubuntu, Chrome Version 48.0.2564.97 (64-bit)

I assume I hit an unintended use case?

Well it will probably affect server side sooner or later...

Chrome V8 4.8.271.17
Node (v5.5.0) V8 4.6.85.31

Accidental global leak, breaks in strict mode

Small issue; k is undefined here (index.js, line 458):

function build_meta_information(object) {
      var res = {
        "timestamp": object.timestamp,
        "version": object.version,
        "changeset": object.changeset,
        "user": object.user,
        "uid": object.uid
      };
      for (k in res)
        if (res[k] === undefined)
          delete res[k];
      return res;
}

add verbouse mode

log conversion process

  • read in data
  • parse (xml/json) data
  • begin actual conversion
  • intermediate steps?

log errors and warnings such as

  • missing node coordinates
  • missing way node references
  • missing way nodes
  • missing relation member references
  • missing relation members
  • incomplete multipolygons
  • missing multipolygon member roles
  • unclosed multipolygon rings
  • non-matching multipolygon rings
  • tainted geometries
  • eventually some more strict multipolygon checks
    • inner/outer intersection
    • touching inner/outer rings
    • self-overlappings of rings

CLI crashes on JSON files > ~256MB

Hi great tool, but I've run into what seems like an arbitrary limitation/bug. I found two OSM Overpass output JSON files that differ by a single way with 4 nodes. The smaller one runs without failure. The larger one crashes consistently with:

FATAL ERROR: CALL_AND_RETRY_0 Allocation failed - process out of memory
Abort trap: 6

When the smaller file runs it requires less than 2GB of memory (out of ~15GB available).
The 1 way / 4 node difference is unremarkable, and is not the cause of the problem.

I know this because if I add space characters to the beginning of the smaller "good" file until it is the size of the larger file, it also fails with the above error. So this seems entirely about file size and not content. I have distilled it down to two files which contain the exact same JSON content (the good smaller file from above), but differ by the amount of leading whitespace added (about 240 bytes)

The file that is 268435577 bytes works, and the one that is 268435578 bytes (with one additional leading space character) fails. 256MB is 268435456 bytes, so these files are both slightly larger than that and maybe it's just a coincidence.

I'm running this on a Mac Mini with OS X 10.9.2 and 16GB of RAM. I'm using node.js version 10.26 installed from MacPorts. The osmtogeojson version is 2.0.4 and was installed from npm.

The "good" file can be obtained from Overpass with this command (assuming the OSM database doesn't change between now and when you try it):

curl -X POST -d '[out:json]; ( node(47.517358482056004,-122.44160651794401,47.728472517944,-122.240223482056); way(bn); rel(bw)["type"="multipolygon"];);( ._; way(r););( ._; node(r)->.x; node(w););out body qt;' http://overpass-api.de/api/interpreter > file.json

This command currently returns a file of 268435336 bytes. If you get more than that try pulling in the bounding box a tiny bit (6th decimal place) until it's less than this amount. That file should convert. Now add about 300 spaces to the beginning of the file until the size is about 268435600 bytes; that one should fail.

I've tried adding these v8 parameters to the node command to increase the memory it will allocate, but it doesn't help (I regularly run node scripts using these parms that consume 10+ GB of memory without any problems):

--max_new_space_size (max size of the new generation (in kBytes))
--max_old_space_size (max size of the old generation (in Mbytes))

Let me know if you need any more info.

De-dupe features with identical id's

If you have a query that can return duplicate records, then osmtogeojson will preserve them. Unfortunately, although it's not explicit in the GeoJSON spec, many consumers of GeoJSON (like CartoDB) expect a feature's identifier (id) property to be unique, and will fail if it isn't. It would be great if osmtogeojson would ensure that features are unique, so that users of the library don't have to.

Add option to sort output GeoJSON features by size.

This is most needed when working with overlapping Polygons.

Possible sorting methods:

  • by feature size (asc/desc)
  • by OSM ID
  • custom sorting functions

Open questions:

  • Let the base ordering (Polygons before Lines before Points) be changed by the user?

Filter additional properties that are included in OSM Files from JOSM

If the osm file is generated by JOSM, osmtogeojson will also include several other properties on each feature that aren't always necessary including:

  • the timestamp (when object was last updated)
  • version
  • uid of last editor
  • user name of last editor
  • changeset (of last object edited)
  • osm id of object.

Here's the same data:

Would you think about including these in the uninteresting tags?
https://github.com/tyrasd/osmtogeojson/blob/2.0.0/index.js#L14

I don't know whether it would be as simple as adding these tags to the uninteresting tags list or not.

custom relation handlers

Let users define their own relation-geometry handlers (e.g. to support more relation types and/or to override built in functionality)?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.