Skip to content

Instantly share code, notes, and snippets.

@craigeley
Created December 30, 2017 16:15
Show Gist options
  • Save craigeley/143a3f8529f04c12c3b1bcef8424abe2 to your computer and use it in GitHub Desktop.
Save craigeley/143a3f8529f04c12c3b1bcef8424abe2 to your computer and use it in GitHub Desktop.
Parse a Google Timeline KML file and convert to geoJSON in order to visualize directly on GitHub.
#!/usr/local/bin/ruby
# Scipt for parsing Google Timeline files to geoJSON
require 'time'
require 'json'
require 'nokogiri'
# To prevent encoding errors on OSX
if RUBY_VERSION =~ /2.*.*/
Encoding.default_external = Encoding::UTF_8
Encoding.default_internal = Encoding::UTF_8
end
# Read from the Google Timeline file and create geoJSON
f = File.open("#{ARGV[0]}")
basename = File.basename(f, ".kml")
kmldoc = Nokogiri::XML(f)
geo = {}
geo[:type] = "FeatureCollection"
geo[:features] = []
kmldoc.xpath('//xmlns:Placemark').each do |place|
if place.css('gx|coord')[1] != nil
array = {"type" => "Feature", :geometry => {:type => "LineString", :coordinates => []}, "properties" => {"stroke-width" => 4}}
pairs = place.css('gx|coord')
place.css('gx|coord').each do |lox|
lon, lat, zero = lox.text.split(/\s/)
array[:geometry][:coordinates].push([lon.to_f,lat.to_f, zero.to_f])
end
else
array = {"type" => "Feature", :geometry => {:type => "Point", :coordinates => []}, :properties => {:name => "", :arrived => "", :left => ""}}
location = place.css('name').text
sTime = place.css('begin').text
eTime = place.css('end').text
array[:properties][:arrived] = Time.parse(sTime).localtime.strftime("%I:%M%p")
array[:properties][:left] = Time.parse(eTime).localtime.strftime("%I:%M%p")
coord = place.css('gx|coord').first.text
lon, lat, zero = coord.split(/\s/)
array[:geometry][:coordinates] = lon.to_f,lat.to_f
array[:properties][:name] = location
end
(geo[:features] ||= []) << array
end
output = JSON.pretty_generate(geo)
out_file = File.new("/path/to/file/#{basename}.geojson", "w+")
out_file.puts(output)
out_file.close
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment