adding multiple polygons in google maps using loops and arrays

- 1 answer

Ad

I want to display some polygons in my google map on loading and added each of them individually. But its a long process and all I want is to create a loop and make that process of initialization and other things easier. I am inserting the code here

 var destinationsi = ["destinations1", "destinations2", "destinations3", "destinations4"];
    var polygon = ["polygon1", "polygon2", "polygon3", "polygon4"];
    var polygonOptions = ["polygonOptions1", "polygonOptions2", "polygonOptions3", "polygonOptions4"];
        for (polygoni = 1; polygoni <= 4; polygoni++ )
        {
        var polygoni = new google.maps.Polygon(polygonOptionsi);
        var polygonOptionsi = {path: destinationsi, strokeColor:"#EDE3D0", strokeWeight:"2", fillColor: '#598BE2', fillOpacity: 0.35};
        polygoni.setMap(map);
        }

But the map is not displaying any polygons in it. How yo make this happpen?

Ad

Answer

Ad

Your JavaScript is all sorts of wrong.

Try this:

//Replace ... with actual latitude and longitude points/arrays
var destinations = [[{lat: -34, lng: 151}, ...], ...];
var polygonOptions;
var polygon;
for (var i = 0; i < destinations.length; i++) {
    polygonOptions = {
        paths: destinations[i], //'path' was not a valid option - using 'paths' array according to Google Maps API
        strokeColor: "#EDE3D0",
        strokeWeight: "2",
        fillColor: '#598BE2',
        fillOpacity: 0.35
    };
    polygon = new google.maps.Polygon(polygonOptions);

    //map needs to be defined somewhere outside of this loop
    //I'll assume you already have that.
    polygon.setMap(map);
}
Ad
source: stackoverflow.com
Ad