2016-03-27 68 views
4

我有一個Mapbox的GL地圖與單層和多層標記,我想更新一個特定的標記,所以我使用setData爲了更新只有一個標記但setData將重置整個圖層標記以僅添加我想要更新爲整個圖層上的單個標記,從而刪除所有舊標記。Mapbox GL setData更新圖層與多個標記

通過努力在以GeoJSON格式添加多個標記爲GeoJSON的對象的數組,如下圖所示,我得到一個錯誤:

Uncaught Error: Input data is not a valid GeoJSON object. 

代碼:

  map.getSource('cafespots').setData([{ 
      "type": "Feature", 
      "geometry": { 
       "type": "Point", 
       "coordinates": [31.331849098205566, 30.095422632059062] 
      }, 
      "properties": { 
       "marker-symbol": "cafe" 
      } 
      },{ 
      "type": "Feature", 
      "geometry": { 
       "type": "Point", 
       "coordinates": [31.39, 30.10] 
      }, 
      "properties": { 
       "marker-symbol": "cafe" 
      } 
      }]); 

會明白,如果這麼多的人可以請告訴我我在做什麼錯誤/缺少這裏,謝謝

回答

10

setData期望一個完整的GeoJSON對象(不只是它的功能)或指向GeoJSON對象的網址。

您需要在代碼中管理GeoJSON的狀態,並在發生更改時通過setData更新整個對象。

var geojson = { 
    "type": "FeatureCollection", 
    "features": [] 
}; 

map.on('load', function() { 
    map.addSource('custom', { 
    "type": "geojson", 
    "data": geojson 
    }); 

    // Add a marker feature to your geojson object 
    var marker { 
    type: 'Feature', 
    geometry: { 
     type: 'Point', 
     coordinates: [0, 0] 
    } 
    }; 

    geojson.features.push(marker); 
    map.getSource('custom').setData(geojson); 
}); 

https://www.mapbox.com/mapbox-gl-js/example/measure/是一個很好的例子,證明了這種行爲。