Jump to content

How to Add Vector Features to an OpenLayers 3 Map

From freem


To add vector features to an OpenLayers 3 map, follow these steps:

1. Define the vector layer: Create a new vector layer using the `ol.layer.Vector` class.

``` var vectorLayer = new ol.layer.Vector({

 source: new ol.source.Vector(),
 style: new ol.style.Style({
   fill: new ol.style.Fill({
     color: 'rgba(255, 255, 255, 0.2)'
   }),
   stroke: new ol.style.Stroke({
     color: '#ffcc33',
     width: 2
   }),
   image: new ol.style.Circle({
     radius: 7,
     fill: new ol.style.Fill({
       color: '#ffcc33'
     })
   })
 })

}); ```

Here, we create a new vector layer with an empty vector source and a custom style that defines the fill, stroke, and image styles for the vector features.

2. Add vector features to the vector source: Create one or more vector features using the `ol.Feature` class and add them to the vector source of the vector layer.

``` var feature = new ol.Feature({

 geometry: new ol.geom.Point(ol.proj.fromLonLat([37.41, 8.82])),
 name: 'My Point'

});

vectorLayer.getSource().addFeature(feature); ```

Here, we create a new point feature with a geometry that is defined in EPSG:3857 projection and add it to the vector source of the vector layer.

3. Add the vector layer to the map: Finally, add the vector layer to the map using the `addLayer` method of the map object.

``` var map = new ol.Map({

 layers: [
   new ol.layer.Tile({
     source: new ol.source.OSM()
   }),
   vectorLayer
 ],
 target: 'map',
 view: new ol.View({
   center: ol.proj.fromLonLat([37.41, 8.82]),
   zoom: 4
 })

}); ```

Here, we create a new map object and add the vector layer to the layers array of the map object. We also set the center and zoom level of the view.

Now, you should be able to see the vector features on your map. You can add more features to the vector source and customize the style of the vector layer as needed.