将google.maps.latlng添加到循环中的数组中 [英] Adding google.maps.latlng to an array within a loop

查看:141
本文介绍了将google.maps.latlng添加到循环中的数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在地图上绘制多边形的代码......不起作用。请告诉我我做错了什么。

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


推荐答案

我不确定是什么你的意思是手动添加点,但我认为问题在于ajax调用是异步的。因此,您正在调用$ .ajax(...),然后直接跳到在之前创建Area 的代码中:您的points数组中包含任何内容:异步调用您的成功函数还没有发生过。

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.

尝试重新安排代码,以便在循环之后创建Area并在成功函数中执行setMap(map)调用。

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

这篇关于将google.maps.latlng添加到循环中的数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆