[GIS] OpenLayers creating Marker Vector Layer

cartographyjavascriptopenlayersopenlayers-2

I have seen over the internet a lot of examples of using Features paste them into the Vector layer and after that insert the layer to the map .

basic example:

 <script>
  var iconFeature = new ol.Feature({
    geometry: new ol.geom.Point([0, 0]),
    name: 'Null Island',
    population: 4000,
    rainfall: 500
  });

  var iconStyle = new ol.style.Style({
    image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
      anchor: [0.5, 46],
      anchorXUnits: 'fraction',
      anchorYUnits: 'pixels',
      opacity: 0.75,
      src: 'data/icon.png'
    }))
  });

  iconFeature.setStyle(iconStyle);

  var vectorSource = new ol.source.Vector({
    features: [iconFeature]
  });

  var vectorLayer = new ol.layer.Vector({
    source: vectorSource
  });

  var rasterLayer = new ol.layer.Tile({
    source: new ol.source.TileJSON({
      url: 'http://api.tiles.mapbox.com/v3/mapbox.geography-class.jsonp',
      crossOrigin: ''
    })
  });

  var map = new ol.Map({
    layers: [rasterLayer, vectorLayer],
    target: document.getElementById('map'),
    view: new ol.View({
      center: [0, 0],
      zoom: 3
    })
  });

In all of those examples they Feature created and put into Vector layer before we create the map but if I want in real time to add some Features.. after I created the map ? how can I do it ?

Best Answer

You can add features to the source after the layer is added to the map. See the API

vectorSource.addFeature(feature); // to add a single feature.
vectorSource.addFeatures(features); // to add a set of features.
Related Question