So, I have the boundaries of every states in the US, from the google map KML file.
This KML file is actually a XML file.
I'm converting this file to a JS file compatible with google map in order to draw polygons on my map.
Here is an excerpt from the file with all the coordinates:
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://earth.google.com/kml/2.2">
<Document>
<Placemark>
<name>WA</name>
<description><![CDATA[]]></description>
<styleUrl>#style37</styleUrl>
<Polygon>
<outerBoundaryIs>
<LinearRing>
<tessellate>1</tessellate>
<coordinates>
-122.402015585862,48.2252165511906
-122.368333031748,48.1281417374007
-122.216991980112,48.0074395523983
-122.230120864997,47.9691133009971
-122.302922293019,47.9502148146411
-122.394492319816,47.7741760704507
-122.414815251142,47.6641799154458
-122.382220450337,47.5954090424224
-122.392633724016,47.510242430349
-122.319738644767,47.3901148739843
-122.325376306437,47.3443234291417
-122.420837154063,47.3188444009071
<!-- etc., 243 points altogether for WA state -->
</coordinates>
</LinearRing>
</outerBoundaryIs>
</Polygon>
</Placemark>
Here is my code to convert the KML file to the JS file.
require 'rubygems'
require 'xmlsimple'
def read_xmlfile(file_name)
file = File.open(file_name, "r")
data = file.read
file.close
return data
end
target = "states.js"
xml_data = read_xmlfile('Stateborders.xml')
data = XmlSimple.xml_in(xml_data, 'KeyToSymbol' => true)
content = "var stateBorders = {\n"
data[:document][0].each_with_index do |item, index|
states = item[1]
states.each_with_index do |state, index|
name = state[:name][0]
coord = state[:polygon][0][:outerboundaryis][0][:linearring][0][:coordinates][0].tr("\t", "").strip.gsub(/[\n]/,") ,new google.maps.LatLng(").gsub(" ) ,", "), ");
coord = state[:polygon][0][:outerboundaryis][0][:linearring][0][:coordinates][0].tr("\t", "").strip
coord2 = ""
coord.split("\n").each do |ll|
ll = ll.split(",")
lat = ll[1].to_s.strip
lat = lat.to_f.round(6).to_s
lon = ll[0].to_s.strip
lon = lon.to_f.round(6).to_s
coord2 << "new google.maps.LatLng("+lat+", "+lon+"), "
end
statecoord = "'#{name}' : [#{coord2}],".gsub(", ],","],")
content << statecoord+"\n"
end
end
content << "};"
File.open(target, "w+") do |f|
f.write(content)
end
The code itself is fast enough but i'm sure can be much simpler/cleaner. Also for the last state I have ],
instead of ]
.