Matthew Colley
Matthew Colley

Reputation: 11466

Google Maps API 3 Javascript Adding Polygon

I am building a polygon from an XML sheet. I am getting this error:

Message: Invalid value for constructor parameter 0: (15.850885, -97.058372)

Here is my code:

downloadUrl(searchUrl, function(data) { 
   var xml = parseXml(data);
   var triangleNodes = xml.documentElement.getElementsByTagName("triangle"); 
   for (var i = 0; i < triangleNodes.length; i++) {
   var trianglelatlng = new google.maps.LatLng(
          parseFloat(triangleNodes[i].getAttribute("triangle_lat")),
          parseFloat(triangleNodes[i].getAttribute("triangle_lng")),
          parseFloat(triangleNodes[i].getAttribute("triangle_lat1")),
          parseFloat(triangleNodes[i].getAttribute("triangle_lng1")),
          parseFloat(triangleNodes[i].getAttribute("triangle_lat2")), 
          parseFloat(triangleNodes[i].getAttribute("triangle_lng2")),
          parseFloat(triangleNodes[i].getAttribute("triangle_lat")),
          parseFloat(triangleNodes[i].getAttribute("triangle_lng")));
          createTriangle(trianglelatlng);
          }

As you can see here I am constructing my polygon array.

Now I am attempting to add the polygon to my map:

function createTriangle(trianglelatlng) { 
  var html2 = "<div id='infodiv'>HelloMatt</div>"; 
    var triangle = new google.maps.Polygon({     
        paths: trianglelatlng,     
        strokeColor: "#FF0000",     
        strokeOpacity: 0.8,    
        strokeWeight: 2,
        zIndex: 7,     
        fillColor: "#FF0000",     
        fillOpacity: 0.35
        });

triangle.setMap(map);

However if I add a static array such as below the polygon will show on the map.

var triangleCoords = [
  new google.maps.LatLng(25.774252, -80.190262),
  new google.maps.LatLng(18.466465, -66.118292),
  new google.maps.LatLng(32.321384, -64.75737),
  new google.maps.LatLng(25.774252, -80.190262)
  ];

I have also declared the var triangle in the global variables. I am certain the issue is in the way I am constructing my array. Hopefully someone has constructed a polygon and can point me in the right direction

Upvotes: 0

Views: 748

Answers (1)

Filippo Mazza
Filippo Mazza

Reputation: 4377

I think that in the first case your var triangleCoords is created only as a LatLng element (see here) while you need an array of LatLng, that you correctly make in the second way you describe. Try to add each point in the for loop to a pre-defined array and use that.

Hope it helps

Upvotes: 1

Related Questions