从文件创建动态变量

时间:2016-07-06 00:50:07

标签: javascript jquery json google-maps

我有一个包含标记的geoJSON文件' ID和每个的Lat和Long。 (见下面的JSON)。

我使用$getJSON访问其属性。

geoJSON文件不断变化(添加或删除标记)。所以,我想要做的是遍历每个标记并创建我的文件所具有的变量数量,然后我将Click事件监听器设置为每个变量。

我喜欢以下内容:

$.getJSON("MyFile.geojson", 
    function(JSON_Result) {
    var JSON_Features_Count = JSON_Result['features'].length;
    for (i=0; i<JSON_Features_Count; i++){
        var coordinates = JSON_Result['features'][i]['geometry']['coordinates']; //Lat = coordinates[1]; Long = coordinates[0]
        var Marker_i = // this variable should be dynamic, because I don't know the number of markers my file has. 
                new google.maps.Marker({
                position: new google.maps.LatLng(coordinates[1],coordinates[0]),
                map: map,
            });
    }
});

以下是我的JSON文件示例:

{
"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },

"features": [
{ "type": "Feature", "properties": { "ID": 1}, "geometry": { "type": "Point", "coordinates": [ -43.256001299999895, -18.966999944999898] } },
{ "type": "Feature", "properties": { "ID": 2}, "geometry": { "type": "Point", "coordinates": [ -43.3659564559999, -18.733241581 ] } },
]
}

1 个答案:

答案 0 :(得分:0)

我更喜欢这样做..

var alldataarr = [];//global variable to store all markers

//loop to deal with jSON
for (var i = 0; i < obj.DATA.length; i++) {
var arrobj = new Object;
arrobj.id = obj.DATA[i].id;
arrobj.district = obj.DATA[i].district;
arrobj.contenttitle = obj.DATA[i].contenttitle;
arrobj.x = obj.DATA[i].x;
arrobj.y = obj.DATA[i].y;
alldataarr.push(arrobj);
GMapCreateMarker(i, obj.DATA[i].x, obj.DATA[i].y, obj.DATA[i].contenttitle, 'camera-web.png')
);

每次更新json文件时,只需修改alldataarr的内容并重新绘制标记。