Convert KML to PolyLine

To convert a KML file to a native Google Maps rendered polyline is essentially the process of parsing the KML, which is XML syntax, into its constituent parts, that being coordinates within a object.

I found the conversion necessary in the process of pulling stored KML data from a Google Fusion Table. If the KML data is stored as Location type, then it will return a MVCArray which can easily be picked apart with for loops to extract the coordinates. However, I have discovered that Fusion Tables has some issues or limitations with very complex KML objects that are not yielding all coordinate arrays, resulting in a half-rendered line. As such I’ve “manually” parsed the KML as a string. The two methods are presented.

success: function(data) {

var rows = data['rows'][0];

for (var i in rows) { 

var geo = rows[i]['geometries'];

	for (var j in geo) { 
	var linesegment = geo[j]['coordinates'];
	drawLine(linesegment);
	};

}


function drawLine(linesegment) { 
	var coordArray = [];
	console.log("rows");
	for (var i in linesegment) {
		var lat = linesegment[i][1];
		var lng = linesegment[i][0];
		var lineCoord = new google.maps.LatLng(lat, lng);
		coordArray.push(lineCoord);
	}

	var randomnumber = Math.floor(Math.random()*7);

	var colors = ["#FF0000", "#00ffff", "#FF00ff", "#Ffff00", "#555555", "#222222"];

  var routeLine = new google.maps.Polyline({
    path: coordArray,
    strokeColor: colors[randomnumber],
    strokeOpacity: 1.0,
    strokeWeight: 4,
  });

  routeLine.setMap(map);
  
}

More Posts

Donate

Hey was this useful? Please consider tipping or subscribing as a member. Even just $1 or $5 can help me improve this content and keep it ad-free.