Search code examples
angularopenstreetmap

Show label and remove marker from map


I use openStreetMap in my Angular 6 application like below. Add a marker to the map works fine but show a label of the marker if clicked on it does not work and actually I dont know why. Also I have no idea how to remove this marker or how an event is sent if the marker is clicked with a single click. Does anyone have hints how I can do it - I tried a lot but without success.

ngOnInit() {
this.map = new ol.Map({
  target: 'map',
  controls: ol.control.defaults({
    attributionOptions: {
      collapsible: false
    }
  }),
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM()
    })
  ],
  view: new ol.View({
    center: ol.proj.fromLonLat([this.latitude, this.longitude]),
    zoom: 10
  })
});

var that = this;
this.map.on('dblclick', function (args) {
  var lonlat = ol.proj.transform(args.coordinate, 'EPSG:3857', 'EPSG:4326');
  var lon = lonlat[0];
  var lat = lonlat[1]; 

  const feature1 = new ol.Feature({
    geometry: new ol.geom.Point(ol.proj.fromLonLat([lon, lat])),
    labelPoint: new ol.geom.Point(ol.proj.fromLonLat([lon, lat])),
    sname: 'My Marker 1'
  });
  const feature2 = new ol.Feature({
    geometry: new ol.geom.Point(ol.proj.fromLonLat([lon+1, lat+1])),
    labelPoint: new ol.geom.Point(ol.proj.fromLonLat([lon+1, lat+1])),
    sname: 'My Marker 2'
  });
  let features = [];
  features.push(feature1);
  features.push(feature2); 

  var layer = new ol.layer.Vector({
      source: new ol.source.Vector({
          features: features
        }),
      style: new ol.style.Style({
          image: new ol.style.Icon({
            anchor: [0.5, 0.5],
            anchorXUnits: "fraction",
            anchorYUnits: "fraction",
            src: "assets/img/marker.png"
          })
        })
    });
  that.map.addLayer(layer);
});
}

Solution

  • You will need a couple of features to achieve your goal,