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);
});
}
You will need a couple of features to achieve your goal,
ol/interaction/Select
, basically let you capture the event of your choice (single click, click, etc.), on the map and let you listen when a feature of a source is selected by the event. Links:
OL API - Select,
OL Examples - Select Featuresol/overlay
, is a widget bound to a location in the map. Links:
OL API - Overlays,
OL Examples - Icon Symbolizer