I am trying to render a map with multiple polylines that are pulled from an external JSON resource. Each JSON record has a number of descriptive fields as well as a field containing an array of LatLngs. The code seems to get the JSON data just fine and to parse it appropriately. I then iterate through each record mapping a polyline but for some reason I cannot get it to display on the map. This is my first time using the Google Maps API. I am probably doing something stupid but having trolled through as many examples as I could find, cannot find anything obviously wrong. All suggestions gratefully received.
The basis for the code for displaying the polylines was taken from the following example: http://code.google.com/intl/no/apis/maps/documentation/javascript/examples/polyline-simple.html
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#map_canvas {
width: 1024px;
height: 700px;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialize(){
var latlng = new google.maps.LatLng(0, 23);
var myOptions = {
zoom: 4,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var url = "http://webstore.thedatahub.org/stevesong/afterfibre/testdata2.json?_limit=3";
var path = [];
$.getJSON(url, function (data) {
// Parse the Linestring field into an array of LatLngs
$.each(data.data, function(index, record) {
line = JSON.parse(record.Linestring);
// Parse the array of LatLngs into Gmap points
for(var i=0; i < line.length; i++){
path.push(new google.maps.LatLng(line[1],line[0]));
}
var polyline = new google.maps.Polyline({
path: path,
strokeColor: '#ff0000',
strokeOpacity: 1.0,
strokeWeight: 3
});
polyline.setMap(map);
});
});
}
// google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body onload="initialize()">
<div id="map_canvas"></div>
</body>
</html>
Thanks to Greg Mahlknecht for providing the final piece of the puzzle. In order to have each JSON record display uniquely as opposed to one giant polyline, the polyline array needs to be reinitialised AFTER each “.each” iteration. Here is the final version that finally does what I was after. Thanks Mitch and Greg.