Created
July 29, 2013 00:37
-
-
Save jesserundle/6101462 to your computer and use it in GitHub Desktop.
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
module KmlParser | |
def self.parse(xml) | |
doc = Nokogiri::XML(xml) | |
output = {} | |
output[:polylines] = [] | |
output[:markers] = [] | |
doc.xpath('//xmlns:Placemark').each do |kmlplacemark| | |
if kmlplacemark.xpath('xmlns:LineString').empty? | |
point = kmlplacemark.xpath('xmlns:Point/xmlns:coordinates').text.split(',').map{|x| x.to_f} | |
icon = doc.css(kmlplacemark.xpath('xmlns:styleUrl').text).xpath('xmlns:IconStyle/xmlns:Icon/xmlns:href').text | |
output[:markers] << { | |
:style => kmlplacemark.xpath('xmlns:styleUrl').text, | |
:name => kmlplacemark.xpath('xmlns:name').text, | |
:description => kmlplacemark.xpath('xmlns:description').text.gsub(/\"/,"\\\""), | |
:point => point, | |
:icon => icon | |
} | |
else | |
coordinates = kmlplacemark.xpath('xmlns:LineString/xmlns:coordinates').text.split("\n").map{|x| x.to_s !~ /,.+,/ ? nil : x.split(',').map{|z| z.to_f}}.compact | |
style = doc.css(kmlplacemark.xpath('xmlns:styleUrl').text) | |
icon = style.xpath('xmlns:IconStyle/xmlns:Icon/xmlns:href').text | |
color = style.xpath('xmlns:LineStyle/xmlns:color').text | |
width = style.xpath('xmlns:LineStyle/xmlns:width').text | |
output[:polylines] << { | |
:style => kmlplacemark.xpath('xmlns:styleUrl').text, | |
:name => kmlplacemark.xpath('xmlns:name').text, | |
:description => kmlplacemark.xpath('xmlns:description').text.gsub(/\"/,"\\\""), | |
:tesselate => kmlplacemark.xpath('xmlns:LineString/xmlns:tessellate').text, | |
:coordinates => coordinates, | |
:icon => icon, | |
:color => "\##{color[2..7]}", | |
:width => width.to_f | |
} | |
end | |
end | |
output | |
end | |
end |
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
desc 'KML Related tasks' | |
namespace :kml do | |
desc 'Push out to JSON' | |
task :to_json => :environment do | |
require Rails.root.join('lib', 'kml_parser.rb') | |
xml = File.read(Rails.root.join('lib', 'sites.kml')) | |
File.open(Rails.root.join('public','sites.json'), 'w') do |sites| | |
sites.write JSON.pretty_generate(KmlParser.parse(xml)) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment