Giter VIP home page Giter VIP logo

togeojson's Introduction

Build status Coverage status stable FOSSA Status

Convert KML and GPX to GeoJSON.

This converts KML & GPX to GeoJSON, in a browser or with Node.js.

  • Tiny
  • Tested
  • Node.js + Browsers

Want to use this with Leaflet? Try leaflet-omnivore!

API

toGeoJSON.kml(doc)

Convert a KML document to GeoJSON. The first argument, doc, must be a KML document as an XML DOM - not as a string. You can get this using jQuery's default .ajax function or using a bare XMLHttpRequest with the .response property holding an XML DOM.

The output is a JavaScript object of GeoJSON data. You can convert it to a string with JSON.stringify or use it directly in libraries like mapbox.js.

toGeoJSON.gpx(doc)

Convert a GPX document to GeoJSON. The first argument, doc, must be a GPX document as an XML DOM - not as a string. You can get this using jQuery's default .ajax function or using a bare XMLHttpRequest with the .response property holding an XML DOM.

The output is a JavaScript object of GeoJSON data, same as .kml outputs.

CLI

Install it into your path with npm install -g @mapbox/togeojson.

~> togeojson file.kml > file.geojson

Node.js

Install it into your project with npm install --save @mapbox/togeojson.

// using togeojson in nodejs

var tj = require('@mapbox/togeojson'),
    fs = require('fs'),
    // node doesn't have xml parsing or a dom. use xmldom
    DOMParser = require('xmldom').DOMParser;

var kml = new DOMParser().parseFromString(fs.readFileSync('foo.kml', 'utf8'));

var converted = tj.kml(kml);

var convertedWithStyles = tj.kml(kml, { styles: true });

Browser

Download it into your project like

wget https://raw.githubusercontent.com/mapbox/togeojson/master/togeojson.js
<script src='jquery.js'></script>
<script src='togeojson.js'></script>
<script>
$.ajax('test/data/linestring.kml').done(function(xml) {
    console.log(toGeoJSON.kml(xml));
});
</script>

toGeoJSON doesn't include AJAX - you can use jQuery for just AJAX.

KML Feature Support

  • Point
  • Polygon
  • LineString
  • name & description
  • ExtendedData
  • SimpleData
  • MultiGeometry -> GeometryCollection
  • Styles with hashing
  • Tracks & MultiTracks with gx:coords, including altitude
  • TimeSpan
  • TimeStamp
  • NetworkLinks
  • GroundOverlays

GPX Feature Support

  • Line Paths
  • Line styles
  • Properties
    • 'name', 'cmt', 'desc', 'link', 'time', 'keywords', 'sym', 'type' tags
    • 'author', 'copyright' tags

FAQ

What is hashing?

KML's style system isn't semantic: a typical document made through official tools (read Google) has hundreds of identical styles. So, togeojson does its best to make this into something usable, by taking a quick hash of each style and exposing styleUrl and styleHash to users. This lets you work backwards from the awful representation and build your own styles or derive data based on the classes chosen.

Implied here is that this does not try to represent all data contained in KML styles.

Why doesn't toGeoJSON support NetworkLinks?

The NetworkLink KML construct allows KML files to refer to other online or local KML files for their content. It's often used to let people pass around files but keep the actual content on servers.

In order to support NetworkLinks, toGeoJSON would need to be asynchronous and perform network requests. These changes would make it more complex and less reliable in order to hit a limited usecase - we'd rather keep it simple and not require users to think about network connectivity and bandwidth in order to convert files.

NetworkLink support could be implemented in a separate library as a pre-processing step if desired.

Should toGeoJSON support feature X from KML?

This module should support converting all KML and GPX features that have commonplace equivalents in GeoJSON.

KML is a very complex format with many features. Some of these features, like NetworkLinks, folders, and GroundOverlays, don't have a GeoJSON equivalent. In these cases, toGeoJSON doesn't convert the features. It also doesn't crash on these constructs: toGeoJSON should be able to run on all valid KML and GPX files without crashing: but for some files it may have no output.

We encourage other libraries to look into supporting these features, but support for them is out of scope for toGeoJSON.

Protips:

Have a string of XML and need an XML DOM?

var dom = (new DOMParser()).parseFromString(xmlStr, 'text/xml');

License

FOSSA Status

togeojson's People

Contributors

amenk avatar asolove avatar averkhaturau avatar bhousel avatar danvk avatar dependabot[bot] avatar elicdavis avatar erikvullings avatar fabriziomoscon avatar fossabot avatar frankrowe avatar giovannirodighiero avatar jfirebaugh avatar joeybaker avatar joukewitteveen avatar jvgeee avatar leplatrem avatar masihyeganeh avatar sainsb avatar santima10 avatar sehaas avatar stafmans avatar starefossen avatar swatinem avatar themarex avatar tmcw avatar tristen avatar tyrasd avatar vool avatar yohanboniface 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  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

togeojson's Issues

-h yields a backtrace

Wouldn't be nice to have inline help instead of this? :)

anarcat@marcos:montreal-rides$ togeojson -h

/usr/local/lib/node_modules/togeojson/togeojson:13
    if (filename.match(/\.kml$/i)) f = 'kml';
                 ^
TypeError: Cannot call method 'match' of undefined
    at Object.<anonymous> (/usr/local/lib/node_modules/togeojson/togeojson:13:18)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:901:3

description cleanup

description should strip \r and \n while parsing. description kml with \r\n create not valid json

failed while install via npm

➜  web-upload git:(master) npm install togeojson
npm WARN package.json [email protected] No repository field.
npm WARN package.json [email protected] No repository field.
npm http GET https://registry.npmjs.org/togeojson
npm http 304 https://registry.npmjs.org/togeojson
npm http GET https://registry.npmjs.org/optimist
npm http GET https://registry.npmjs.org/concat-stream
npm http GET https://registry.npmjs.org/xmldom
npm http 304 https://registry.npmjs.org/concat-stream
npm http 304 https://registry.npmjs.org/xmldom
npm ERR! Failed to parse json
npm ERR! Unexpected end of input
npm ERR! File: /home/howard/.npm/xmldom/0.1.19/package/package.json
npm ERR! Failed to parse package.json data.
npm ERR! package.json must be actual JSON, not just JavaScript.
npm ERR! 
npm ERR! This is not a bug in npm.
npm ERR! Tell the package author to fix their package.json file. JSON.parse

npm ERR! System Linux 3.11.0-17-generic
npm ERR! command "node" "/usr/bin/npm" "install" "togeojson"
npm ERR! cwd /home/howard/Documents/DataGarage/web-upload
npm ERR! node -v v0.10.26
npm ERR! npm -v 1.4.4
npm ERR! file /home/howard/.npm/xmldom/0.1.19/package/package.json
npm ERR! code EJSONPARSE
npm http 304 https://registry.npmjs.org/optimist
npm ERR! 
npm ERR! Additional logging details can be found in:
npm ERR!     /home/howard/Documents/DataGarage/web-upload/npm-debug.log
npm ERR! not ok code 0

Placemark ID does not get converted

Something like

<Placemark id="ID_00019" >
        <name>example</name>
        <id>19</id>
...
</Placemark >

Does not get converted into json

I've reached a work around to fetch the Placemark id
placemarks[0].getAttribute("id");

Parse heart rate data in gpx extensions

   <trkpt lat="37.7833760" lon="-122.4072760">
    <ele>11.5</ele>
    <time>2015-01-19T21:24:25Z</time>
    <extensions>
     <gpxtpx:TrackPointExtension>
      <gpxtpx:hr>121</gpxtpx:hr>
     </gpxtpx:TrackPointExtension>
    </extensions>
   </trkpt>

Sample comes from Strava.

Parse the "folder" tag

Hi, first of all, you have my thanks for a very nice parser.
Now for the issue: the folder tag divides the data into meaningful groups/layers. I could not see that toGeoJson handles it - it seems to be ignored. Am I missing something?

Styles no longer work from Google maps output

Not sure about other sources but Google maps at least has added the tag, which has the id that the data nodes map to, instead of the <Style> tags having it. The style tags have "abc123-normal" and "abc123-highlight", which this module doesn't pick up on, so the styleUrl tag is not being set, and therefore style items are being ignored.

Link Tag Issue

Hi and thanks for GeoJSON
Link Tags in GPX files are not translating to properties.

source:
<link href="http://www.ayeltd.biz"><text>AYE Ltd.</text></link>
result:
feature link property = does not exist

source:
<link href="http://www.ayeltd.biz">
    <text>AYE Ltd.</text>
</link>
result:
feature link property "\n     " (a control char)

Not sure how they should translate,You can separate attributes and node values.
link.attribs.href=http://www.ayeltd.biz
link.text="AYE Ltd."
Or dont convert links.
Hope this is useful.

Bower broken on 0.8 branch

Bower works on 0.7 branch:

$ bower install git://github.com/mapbox/togeojson.git#0.7
bower togeojson#0.7             cached git://github.com/mapbox/togeojson.git#0.7.0
bower togeojson#0.7           validate 0.7.0 against git://github.com/mapbox/togeojson.git#0.7
bower togeojson#0.7            install togeojson#0.7.0

togeojson#0.7.0 client/bower_components/togeojson

But not on 0.8 one:

$ bower install git://github.com/mapbox/togeojson.git#0.8
bower togeojson#0.8         not-cached git://github.com/mapbox/togeojson.git#0.8
bower togeojson#0.8            resolve git://github.com/mapbox/togeojson.git#0.8
bower togeojson#0.8           download https://github.com/mapbox/togeojson/archive/v0.8.0.tar.gz
bower togeojson#0.8            extract archive.tar.gz
bower togeojson#0.8           EINVALID Failed to read /tmp/toub/bower/togeojson-737-WB3MCo/bower.json

Any way of doing JSON -> KML?

Hi!

Is there a way to do a reverse convertion with togeojson?
// I that it's not its main function from the name, but nevertheless

IE9 support

This has come up a few times in support... I'm not sure how much to sell the soul to the past but supporting this may be simple / famous last words

Fuzz input testing

Generating random XML would make blowing through potential fails faster.

How to use as a library?

Hi,
I've downloaded the toGeoJson file into my computer (windows 7 64 bit if it matters).
I've added it to my dependency manager (using requireJS).
I can see the file loading, but the toGeoJson is not available in my scope.
Any idea why? Is there another file I need to download?

Unused second param

In the example there is a way to pass params in method.

For example tj.kml(kml, { styles: true })
But it doesn't make any effect.

In code I found only one occurrence of this param:
o = o || {};

Is it deprecated methods?

Jsdom does not support nodejs anymore

Starting from version 4, jsdom is not supporting nodejs anymore, meaning the nodejs example mentioned in the readme is not working anymore.
The easiest fix for now would be a note saying that "you should use jsdom <= version 3".
Since this is not a proper long term solution, I was wondering, if anyone knows a module similar to jsdom for parsing. If so, I could update the readme, if you want to.

GPX support?

Any thought on adding support for GPX to GeoJSON?

leaflet

i dont get it too work with Leaflet. Can you give an example?

strange symbol causes error

This is a very strange bug:
Using today's togeojson.js (Download ZIP and extract), Firebug throws the following error:

SyntaxError: missing ; before statement
v = v ||Â "";
Line 91

There is something wrong with the blank. When deleting this invisible letter and inserting a normal blank, the error is gone.

v = v || "";

GeoRSS?

Hey @tmcw
I'm planning to add GeoRSS support to uMap.
Are you interested if I (try to) add it to this module?
I'm not sure it's a good idea, given that the standard seem quite a mess, and I'm not sure it can be easily turned into a clean generic tool.
But if you are interested too, it's worth an attempt :)

Yohan

Styles not transalated to geojson

I am trying to transform KML to geojson as follows in my nodejs application:

  var kml = jsdom(fs.readFileSync('test.kml', 'utf8'));
  var geojson = toGeoJson.kml(kml, { styles: true });

But I am not getting a styleUrl property.

Tried to test with style.kml in your test data folder.

Output is:

{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
-122.0822035425683,
37.42228990140251,
0
]
},
"properties": {
"name": "Google Earth - New Polygon",
"description": "Here is some descriptive text"
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
-122.0822035425683,
37.42228990140251,
0
]
},
"properties": {
"name": "Google Earth - New Path"
}
}
]
}

Include elevation data

Forgive me if this is ommitted for a reason, I'm pretty new to geoJSON...

However it appears from the spec that for each coordinate, a 3rd elevation value is supported. If this data exists in the source file, it would be useful if this was included in the geoJSON coordinates.

trkseg can have less than two trkpt

See http://www.topografix.com/GPX/1/1/gpx.xsd

<xsd:element name="trkpt" type="wptType" minOccurs="0" maxOccurs="unbounded">

As we now are outputing one array per trkseg this can result in an invalid geojson: "For type "LineString", the "coordinates" member must be an array of two or more positions."

That said, I'm not sure what would be the behaviour of togeojson in this case.
I see three option:

  • don't care, it's the responsibility of the user to validate output geojson
  • skip (feature if LineString, feature or segment when MultiLineString)
  • try to merge (this was done, I guess not on purpose, before the recent implementation of MultiLineString support)

I can propose a patch if needed, but first I wanted to have the discussion.

My personal opinion is that we should do needed checks not to return an invalid geojson. In this case I would skip (I prefer omission of data than creation of "wrong" data).

@tmcw ? :)

GeoJSON to KML?

Ever thought of going the other direction. I.E. GeoJSON to KML.

CDATA section ignored in KML description

I've noticed some issues parsing CDATA sections in a KML file

This doesn't work;

      <description>
        <![CDATA[
             Here is some text
        ]]>
      </description>

but this does;

      <description><![CDATA[Here is some text]]></description>

and this also;

      <description><![CDATA[

             Here is some text
      ]]></description>

As far as I know they're all valid. Nevertheless a bug?

MultiGeometry

This is the only real remaining task here.

Either multigeometries always yield multiple features, or multis with the same kind of type get condensed into Multi(poly,point,line).

KML being parsed with newline and whitespace into the properties

I'm working with a .kml file provided by Trimet in Oregon. The kml looks like this:

<Data name="route_number">
          <value>
            23
          </value>
        </Data>
        <Data name="direction">
          <value>
            1
          </value>
        </Data>
        <Data name="route_description">
          <value>
            San Rafael
          </value>
        </Data>
        <Data name="public_route_number">
          <value>
            23
          </value>
        </Data>
        <Data name="direction_description">
          <value>
            To Gateway Transit Center
          </value>
        </Data>

When this is parsed using toGeoJSON.kml(xml), I end up with strings that contain newline characters and white-space, which corresponds to the format of the kml. The output ends up looking like this:

{"properties" : {
"direction_description": "\n                To Gateway Transit Center\n              "
}}

Is the intent for the newlines and whitespace to be included in cases where the kml is formatted like it is in my example?

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.