David - Musings of an SRE

Converting KML into GeoJSON for Mongoimport & Querying

First, you need to install kml2geojson.

Luckily, there’s pip.

$ pip install kml2geojson

Once that’s done, you can take a .kml file and convert it into a GeoJSON format. Why GeoJSON? Because its gaining in support (MongoDB, RethinkDB) and has lots of smart people working on its specification.

$ kml2geojson <.kml> <output_path>

Now if you’re looking to import the geoJSON data into MongoDB so that you can do geospatial queries, you’ll need to prepare the GeoJSON file for import so that MongoDB will create multiple documents rather than a single document of your geo-objects.

Install JQ.

This helps prepare the geojson file to be imported into mongo as individual documents rather than one giant document.

$ apt-get install jq

Process away!

$ jq --compact-output ".features[]" input.geojson > output.geojson
$ mongoimport -d <database> -c <collection> output.geojson

With your geospatial data now in your MongoDB, you can now do something like:

// in your database,
db.runCommand({ geoNear: '<collection>', near: [103.87059593, 1.3661834], spherical: true}).results

And it will return you the nearest geo-objects closest to the given lat/long.


Note: MongoDB uses a [lng,lat] convention over the normal [lat,lng]. So when you input your near query, make sure its not written wrongly! Side Note: Also, do note that the dis key returned from the above runCommand is in radians so to convert to kilometers, you’ll need to multiple the result by 6378.1