5

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?

5

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:

var iconGeometry = new ol.geom.Point([637125.42195, 8172199.19090669]);

var iconFeature = new ol.Feature({
        geometry: iconGeometry,
        name: 'Null Island',
        population: 4000,
        rainfall: 500
    });

2: Updating the geometry with the setCoordinates() function:

    map.on('singleclick', function (evt) {
        iconGeometry.setCoordinates(evt.coordinate);
    });
2
  • Thank you :) Was looking in a documentation for this method, but all the time got solution only for previous version of OpenLayers
    – Tonven
    Sep 16 '14 at 10:55
  • Excellent answer. Thanks for going the extra mile and making the fiddle. Jan 6 '17 at 15:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.