[GIS] Clicking to create multiple icons on map using OpenLayers 4

openlayers

I am trying to build python-based (flask) application where multiple icons can be
placed on an openstreetmap by clicking on the various spots where I want an icon. I am trying to
achieve that using OpenLayers 4. Here is what I have tried:

var iconStyle = new ol.style.Style({
   image: new ol.style.Icon({
      size: [21, 25],
      offset: [0, 0],
    //  src: 'C:\flask_apps\click_coord\images\mark.png'
      src:'{{url_for('static', filename='mark.png')}}'
   })
});

var map = new ol.Map({

   layers: [
      new ol.layer.Tile({
        source: new ol.source.OSM()
      })
    ],
   target: 'map',
   view: new ol.View({
     center: [0, 0],
     zoom: 2
   })
 });

var vectorSource = new ol.source.Vector();

var source_name = 'iconSource';
vectorSource.set('name',source_name);

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


var layer_name = 'iconLayer';

vectorLayer.set('name',layer_name); 

map.addLayer(vectorLayer);


map.on('click', function(evt) {
   var position = evt.coordinate;

   var mlayers = map.getLayers();
   var length = mlayers.getLength(), l;

   for (var i = 0; i < length; i++) {
      l = mlayers.item(i);


     if(layer_name ===l.get('name')) {


       var iconFeature = new ol.Feature({
         geometry: new ol.geom.Point(ol.proj.transform([position], 'EPSG:4326',     
         'EPSG:3857'))

       });

       iconFeature.setStyle(iconStyle);

       this.vectorLayer.getSource().addFeature(iconFeature);
       this.vectorLayer.clear();
       //   this.vectorLayer.redraw();
       //   this.vectorLayer.changed();
       //   this.vectorLayer.refresh({force:true});

     }  
   }

 });  

I have checked using view page source that the framework is resolving the path to the icon image
properly. I had previously hard-coded the location of the icon image. Irrespective of what I try, nothing
happens when I click the map. I have tried refreshing the map (I may not be doing this properly), that
doesn't seem to work either.

Could someone point out what I am doing wrong?

I am using OpenLayers 4.2.0

Best Answer

I found the issue. Actually you don't need to transform your point geometry from EPSG:4326 to EPSG:3857, since the map is already in EPSG:3857. As stated in the openlayers doc, the default projection of the map is always EPSG:3857.

So change your code as:

   var iconFeature = new ol.Feature({
      geometry: new ol.geom.Point(position)
   });

I also remove the this before the vectorLayer.getSource().addFeature(iconFeature); because it refers to the evt.

vectorLayer.getSource().addFeature(iconFeature);

I got also an error with vectorLayer.clear() which was not recognized, so I remove this line.

I tried this on Google Chrome 59.0.3071.11 with openlayers 3.8.2.