Last active
October 6, 2020 13:00
-
-
Save eliotk/7744806 to your computer and use it in GitHub Desktop.
A ruby script to parse My Tracks kml files and aggregate the summary data into one CSV file to chart changes in time series (or otherwise)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'nokogiri' | |
require 'csv' | |
kml_path = '/path/to/Google Drive/My Tracks/' | |
def kml_file_paths path | |
Dir.glob(path + "*.kml") | |
end | |
csv = CSV.open('mytracks.csv', "wb") | |
kml_file_paths(kml_path).each_with_index do |file_path, index| | |
kml = File.read(file_path) | |
doc = Nokogiri::XML(kml) | |
# summary data is stored as cdata in the last Placemark entity's description child node | |
desc_lines = doc.search('description').last.text.split(/\n/) | |
# remove first two noncrucial lines | |
desc_lines.shift(2) | |
# modify total distance value to be numeric and in miles | |
if desc_lines[3] | |
desc_lines[3] = desc_lines[3].gsub(/(?<=: )(.+)/, desc_lines[3].scan(/\(([0-9.]+).+\)/)[0][0]) | |
end | |
# modify avg moving speed value to be numeric and in miles | |
if desc_lines[7] | |
desc_lines[7] = desc_lines[7].gsub(/(?<=: )(.+)/, desc_lines[7].scan(/\(([0-9.]+).+\)/)[0][0]) | |
end | |
# assign MyTrack keys as CSV headers | |
if index == 0 | |
csv << desc_lines.map {|key_val| key_val.split(': ', 2).first} | |
end | |
csv << desc_lines.map {|key_val| key_val.split(': ', 2).last} | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
tks!!