【问题标题】:Create dynamic variables from file从文件创建动态变量
【发布时间】:2016-07-06 00:50:06
【问题描述】:

我有一个 geoJSON 文件,其中包含标记的 ID 以及每个标记的纬度和经度。 (见下面的 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 ] } },
]
}

【问题讨论】:

    标签: javascript jquery json google-maps


    【解决方案1】:

    我更喜欢这样做..

    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的内容,重新绘制标记即可。

    【讨论】:

      猜你喜欢
      • 2014-01-12
      • 1970-01-01
      • 1970-01-01
      • 2014-10-17
      • 1970-01-01
      • 2021-12-19
      • 2019-12-10
      • 2021-10-26
      • 2011-10-27
      相关资源
      最近更新 更多