2

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();
}

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Actually laughed out loud... after spending three hours last night working on this, I saw your answer and dragged the code up into the success function, and it worked perfectly first time. Thanks so much :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.