Lewis Buckley
Lewis Buckley

Reputation: 1612

Adding google.maps.latlng to an array within a loop

This is my code to draw a polygon on a map... which doesnt work. Please tell me what I'm doing wrong.

If I add points manually like this:

points.push(new google.maps.LatLng(51.35020072, -2.978521717));
points.push(new google.maps.LatLng(51.35047285, -2.971755353));
points.push(new google.maps.LatLng(51.34943740, -2.969097019));

instead of using the loop it works fine. Any ideas?

    function drawpolygon(areaid) {

    var points = []; 

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "polygons.asmx/GetPolygonsByArea",
        data: '{ id: "' + areaid + '" }',
        dataType: "json",
        success: function (msg) {
            var c = eval(msg.d);
            for (var i in c) {

                var lat = parseFloat(c[i][1]);
                var lng = parseFloat(c[i][2]);

                points.push(new google.maps.LatLng(lat, lng));

            }
        }
    });

    var Area;

    Area = new google.maps.Polygon({
        paths: points,
        strokeColor: "#204F68",
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: "#A1CBE2",
        fillOpacity: 0.35
    });

    Area.setMap(map);

    google.maps.event.addListener(Area, 'click', showArrays);
    infowindow = new google.maps.InfoWindow();
}

Upvotes: 2

Views: 2404

Answers (1)

John Black
John Black

Reputation: 621

I'm not sure what you mean by "adding points manually", but I think the problem is that the ajax call is asynchronous. So, you're caling "$.ajax(...)" and then falling right through to the code that creates Area before your points array has anything in it: the asynchronous call to your success function hasn't happened yet.

Try rearranging your code so you create Area and do the setMap(map) call in your success function, right after the loop.

Upvotes: 5

Related Questions