Search code examples
javascriptgoogle-mapswkt

Pushing Google Map Polygons/Markers to array pushes no data


I am creating a tool using Google Maps API v3. I need overlay some polygons and markers, and clear them.

I was attempting to follow an example similar to this - push polygons/markers into an array, and then delete them from the array, and thus the map.

However, when I push a polygon or marker into my array, the resulting array value is always "undefined", though my polygons and markers appear correctly on the map.

Note: I am using wicket to read WKT from my db into google maps.

Function below is having the issue - an id is sent to functions.php, the WKT for that ID is returned, and it is mapped - and should be pushed into the array, but is not.

I have tried setting the polygon/markers to a variable, and pushing that to the array, but that also did not work.

var layersArr = [];

function getGeo(id){
    $.ajax({
        url: 'functions.php',
        type: 'POST',
        data: {
            request: 'getGeo',
            id: id
        },
        success: function(data){
            wkt.read(data);

            switch(wkt.type){
                case 'polygon':
                case 'multipolygon':
                    layersArr.push(new google.maps.Polygon(wkt.toObject()).setMap(map));
                    break;
                case 'point':
                    layersArr.push(new google.maps.Marker(wkt.toObject()).setMap(map));
                    break;
                default:
                    alert('Unrecognized wkt type');
                    return;
                    break;
            }
        },
        error: function(jqXHR, text, error){
            ajaxError(jqXHR, text, error);
        }
    });
}

Solution

  • It is because setMap() has no return value according to Google Maps API v3.

    Instead of this:

    layersArr.push(new google.maps.Polygon(wkt.toObject()).setMap(map));

    You need to do this:

    var poly = new google.maps.Polygon(wkt.toObject());
    layersArr.push(poly);
    poly.setMap(map);