2016-07-06 138 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的內容並重新繪製標記。