nBishop nBishop - 4 months ago 88
Javascript Question

Drawing Multiple Polygons on Google Maps API v3 from MySQL database

So, I am attempting to draw multiple polygons onto a google map via polygon spatial data from my MySQL table. I have a php script that outputs the following XML based off my table data.

<subdivision name="Auburn Hills">
<coord lat="39.00748" lng="-92.323222"/>
<coord lat="39.000843" lng="-92.323523"/>
<coord lat="39.000509" lng="-92.311592"/>
<coord lat="39.007513" lng="-92.311378"/>
<coord lat="39.00748" lng="-92.323222"/>
</subdivision>
<subdivision name="Vanderveen">
<coord lat="38.994206" lng="-92.350645"/>
<coord lat="38.985033" lng="-92.351074"/>
<coord lat="38.984699" lng="-92.343092"/>
<coord lat="38.981163" lng="-92.342234"/>
<coord lat="38.984663" lng="-92.3335"/>
<coord lat="38.993472" lng="-92.333179"/>
<coord lat="38.994206" lng="-92.350645"/>
</subdivision>


My issue is that the javascript I am using to try and draw each shape onto the map is returning odd coordinates. using an alert, I can see that the array that is meant to store the coordinates for the "new google.maps.Polygon" is returning the first latitude and longitude pair for each shape and drawing a line segment as opposed to the full polygon. The problematic javascript is below.

function initialize() {
var mapOptions = {
...
};

var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var arr = new Array();
var polygons = [];

downloadUrl("subdivision-coordinates.php", function(data) {
var xml = data.responseXML;
var subdivision = xml.documentElement.getElementsByTagName("subdivision");
for (var i = 0; i < subdivision.length; i++) {
var coordinates = xml.documentElement.getElementsByTagName("subdivision")[i].getElementsByTagName("coord");
arr.push( new google.maps.LatLng(
parseFloat(coordinates[i].getAttribute("lat")),
parseFloat(coordinates[i].getAttribute("lng"))
));

polygons.push(new google.maps.Polygon({
paths: arr,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
}));
polygons[polygons.length-1].setMap(map);
}
});
}
function downloadUrl(url, callback) {
..blah..blah stuff from google
}
function doNothing() {}
google.maps.event.addDomListener(window, 'load', initialize);


The issue seems to be clearly related to how I am pushing the data into the array "arr". I've tried a few different methods of handling it and nothing seems to be working (I am admittedly a novice when it comes to javascript). Any advice would be greatly appreciated!

Answer

The google.maps.Polygon paths property takes an array of arrays of google.maps.LatLngs. You need to process through each subdivision as its own array and either push it as a separate path into the one polygon or (as below) create a new polygon for each.

    var subdivision = xml.getElementsByTagName("subdivision");
    for (var i = 0; i < subdivision.length; i++) {
        arr = [];
        var coordinates = xml.documentElement.getElementsByTagName("subdivision")[i].getElementsByTagName("coord");
        for (var j=0; j < coordinates.length; j++) {
          arr.push( new google.maps.LatLng(
                parseFloat(coordinates[j].getAttribute("lat")),
                parseFloat(coordinates[j].getAttribute("lng"))
          ));

          bounds.extend(arr[arr.length-1])
        }
        polygons.push(new google.maps.Polygon({
            paths: arr,
            strokeColor: '#FF0000',
            strokeOpacity: 0.8,
            strokeWeight: 2,
            fillColor: '#FF0000',
            fillOpacity: 0.35
        }));
        polygons[polygons.length-1].setMap(map);
    }

working fiddle

code snippet:

function initialize() {
  var mapOptions = {
    zoom: 5,
    center: new google.maps.LatLng(40, -117),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  var arr = new Array();
  var polygons = [];
  var bounds = new google.maps.LatLngBounds();

  // downloadUrl("subdivision-coordinates.php", function(data) {
  var xml = xmlParse(xmlString);
  var subdivision = xml.getElementsByTagName("subdivision");
  // alert(subdivision.length);
  for (var i = 0; i < subdivision.length; i++) {
    arr = [];
    var coordinates = xml.documentElement.getElementsByTagName("subdivision")[i].getElementsByTagName("coord");
    for (var j = 0; j < coordinates.length; j++) {
      arr.push(new google.maps.LatLng(
        parseFloat(coordinates[j].getAttribute("lat")),
        parseFloat(coordinates[j].getAttribute("lng"))
      ));

      bounds.extend(arr[arr.length - 1])
    }
    polygons.push(new google.maps.Polygon({
      paths: arr,
      strokeColor: '#FF0000',
      strokeOpacity: 0.8,
      strokeWeight: 2,
      fillColor: '#FF0000',
      fillOpacity: 0.35
    }));
    polygons[polygons.length - 1].setMap(map);
  }
  // });
  map.fitBounds(bounds);
}
var xmlString = '<subdivisions><subdivision name="Auburn Hills"><coord lat="39.00748" lng="-92.323222"/><coord lat="39.000843" lng="-92.323523"/><coord lat="39.000509" lng="-92.311592"/><coord lat="39.007513" lng="-92.311378"/><coord lat="39.00748" lng="-92.323222"/></subdivision><subdivision name="Vanderveen"><coord lat="38.994206" lng="-92.350645"/><coord lat="38.985033" lng="-92.351074"/><coord lat="38.984699" lng="-92.343092"/><coord lat="38.981163" lng="-92.342234"/><coord lat="38.984663" lng="-92.3335"/><coord lat="38.993472" lng="-92.333179"/><coord lat="38.994206" lng="-92.350645"/></subdivision><subdivisions>';

/**
 * Parses the given XML string and returns the parsed document in a
 * DOM data structure. This function will return an empty DOM node if
 * XML parsing is not supported in this browser.
 * @param {string} str XML string.
 * @return {Element|Document} DOM.
 */
function xmlParse(str) {
  if (typeof ActiveXObject != 'undefined' && typeof GetObject != 'undefined') {
    var doc = new ActiveXObject('Microsoft.XMLDOM');
    doc.loadXML(str);
    return doc;
  }

  if (typeof DOMParser != 'undefined') {
    return (new DOMParser()).parseFromString(str, 'text/xml');
  }

  return createElement('div', null);
}

google.maps.event.addDomListener(window, 'load', initialize);
#map-canvas,
body,
html {
  height: 100%;
  width: 100%;
}
<script src="http://maps.google.com/maps/api/js"></script>
<div id="map-canvas"></div>

Comments