2

我有以下问题代码进一步向下。当我这样做时

city[i] = response[i].name;

我可以打印出我拥有的每个城市的每个名字。但是现在我想要一个多维数组,因为我还想保存以下代码

L.marker([response[i].lat, response[i].lon]).bindPopup(response[i].name);

而且我认为我可以将它保存在一个多维数组中,所以当我们有一个例子

city[1]["CityName"] = "New York"
city[1]["Locations"] =  L.marker([location]).bindPopup(name);

所以,现在当我打电话时,city[1]['Locations']我得到了 L.Marker,对吧?

这是我的代码

function init()
{
region = 'all';
var url = "http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
    attribution = "(c) OSM contributors, ODBL";

var minimal = L.tileLayer(url, {styleID: 22677, attribution: attribution});
$.ajax
({
    type: 'GET',
    url: 'webservice.php',
    data: {region: region},
    success: function(response, textStatus, XMLHttpRequest) 
    { 
        var city = new Array();
        var lygStr = '';
        for(var i = 0; i < response.length; i++)
        {
            //alert(response[i].lat + " | " + response[i].lon + " | " + response[i].name);
            alert(response[i].name);
            city[i]["CityName"] = response[i].name;

            //L.marker([response[i].lat, response[i].lon]).bindPopup(response[i].name);
            if(i + 1 == response.length)
            {
                lygStr += city[i]["CityName"];
            }
            else
            {
                lygStr += city[i]["CityName"] + ", ";
            }
        }
        alert("Test" + lygStr);
        var cities = L.layerGroup([lygStr]);

        map = L.map("map1", 
        {
            center: new L.Latlng(resposne[1].lat, response[0].lon),
            zoom: 10,
            layers: [minimal, cities]
        });
    }
});

}
4

3 回答 3

2

正确的初始化将解决此问题 - 您需要将位置处city[i]的对象初始化为保存您的值而不是未定义的对象。

    var city = [];   // don't use new Array() !
    var lygStr = '';
    for(var i = 0; i < response.length; i++)
    {
        city[i] = {}; // you need to create an object here

        city[i]["CityName"] = response[i].name;

此外,您希望拥有一个对象而不是数组。数组只能有数字索引,而对象可以有你想要的标识符。

    city[i]['Location']
    // same as
    city[i].Location
于 2013-04-12T12:27:46.553 回答
0

它看起来像在这一行:

city[1]["Locations"] =  L.marker([location]).bindPopup(name);

city[1]["Locations"]将被设置为任何.bindPopup(name)回报。这可能是undefined或者它可能是一个函数。该方法是否构造为返回其调用的对象?仅此而已:

city[1]["Locations"] =  L.marker([location]);
city[1]["Locations"].bindPopup(name);
于 2013-04-12T12:29:39.500 回答
-1

在声明它之前,您将city[i]其用作数组:

var city = []; // don't use the new Array(); syntax
var lygStr = '';

for(var i = 0; i < response.length; i++) {
    // before using city[i] as an array, you must declare it as an array
    city[i] = [];    

    city[i]["CityName"] = response[i].name;
    ...
于 2013-04-12T12:28:03.933 回答