2016-07-06 135 views
0

我有一个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 ] } }, 
] 
} 

回答

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