Skip to content

Instantly share code, notes, and snippets.

@pn11
Last active June 1, 2019 10:08
Show Gist options
  • Save pn11/a43555e5cd386f44d2ff to your computer and use it in GitHub Desktop.
Save pn11/a43555e5cd386f44d2ff to your computer and use it in GitHub Desktop.
Convert GPX to GeoJSON. GPXをGeoJsonに変換する。

Convert GPX to GeoJSON

By running

ruby gpx2geojson.rb test.gpx

test.csv will be created. Then use mapbox/csv2geojson to make .geojson file.

npm install -g csv2geojson
csv2geojson test.csv > test.geojson

test.csv is like this:

lat, lon
35.721219, 139.766585
35.721155, 139.766634
35.721209, 139.766607
35.721176, 139.766655
35.721225, 139.766655
35.721268, 139.766623
35.72131, 139.76658

GeoJSON file like this will be created.

#!/usr/bin/ruby
# -*- coding: utf-8 -*-
require "rexml/document"
in_file_name = ARGV[0]
out_file_name = in_file_name.gsub(".gpx", ".csv")
fout = File.open(out_file_name, "w")
fout.puts "lat, lon"
doc = nil
File.open(in_file_name) {|xmlfile|
doc = REXML::Document.new(xmlfile)
}
trkseg = doc.elements["/gpx/trk/trkseg"]
trkseg.elements.each("trkpt"){|trkpt|
longtitude = trkpt.attributes.get_attribute("lon")
latitude = trkpt.attributes.get_attribute("lat")
fout.puts "#{latitude}, #{longtitude}"
}
fout.close
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment