问题
I am having issues trying to implement a dynamic marker in my OpenLayer Map widget. I would like that a marker/point is placed on the map "onclick". Instead of placing a new marker/point each mouse click, I would like the marker to be be refreshed on the new position. I have been trying to find some documentation on the layers/vectors and having difficulties understanding how to refresh/replace the layer...
Here is my current OL code for my map that updates two inputs with the latitude and longitude on mouse click:
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
],
view: new ol.View({
center: ol.proj.fromLonLat([37.41, 8.82]),
zoom: 4
})
});
map.on('click', function(evt){
var lonlat = ol.proj.transform(evt.coordinate, 'EPSG:3857', 'EPSG:4326');
var lon = lonlat[0];
var lat = lonlat[1];
document.getElementById("latitude").value = lat;
document.getElementById("longitude").value = lon;
});
Thanks in advance!
回答1:
If your marker is a point feature something like this should do it
map.on('click', function(evt){
myMarker.getGeometry().setCoordinates(evt.coordinates);
});
来源:https://stackoverflow.com/questions/55598816/dynamically-change-point-marker-on-click-openlayers-5