I have the following code for displaying OSM with a predefined feature. I am using OpenLayers3:
var wmsLayer = new ol.layer.Tile({
source: new ol.source.OSM()
});
var view = new ol.View({
center: [637125.42195, 8172199.19090669],
zoom: 14
});
var iconFeature = new ol.Feature({
geometry: new ol.geom.Point([637125.42195, 8172199.19090669]),
name: 'Null Island',
population: 4000,
rainfall: 500
});
var iconStyle = new ol.style.Style({
image: new ol.style.Icon(({
anchor: [0.5, 46],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
opacity: 0.75,
src: 'https://evernote.com/media/img/getting_started/skitch/android/android-location_icon.png'
}))
});
iconFeature.setStyle(iconStyle);
var vectorSource = new ol.source.Vector({
features: [iconFeature]
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource
});
var map = new ol.Map({
layers: [wmsLayer, vectorLayer],
target: 'map',
view: view,
//controls: []
});
map.on('singleclick', function (evt) {
var position = evt.coordinate;
});
How I can change the location of the marker in the click event now?
Best Answer
Very nice and well considered code. What you have missed is updating the coordinates of the point object in the event, not only storing them in a variable. The easiest way to achieve this is getting the geometry property of the icon and updating it in the
singleclick
event. I have created a fiddle to show it.The main changes are the following:
1: Grabbing the geometry of the feature from the iconFeature object:
2: Updating the geometry with the
setCoordinates()
function: