Dan-Levi Tømta
Dan-Levi Tømta

Reputation: 846

how can i dynamically update a ol.Features geometry property ( coordinates ) in OpenLayers 3

Im just getting started with OpenLayers 3 and i am trying to dynamically update a Features geometry property with coordinates, obviously there is something that i am missing out because the Feature is not moving. Here is what i god so far:

Socket.IO

socket.on('mapData', function(mapData) {
    if (mapisloaded) {
            latLon = ol.proj.transform([mapData.lon, mapData.lat], 'EPSG:4326', 'EPSG:3857');
        // Initiate latlong object with mapData
        if (centerIsRequested) {

            //Center map with mapData
        };

        // Update marker with latlong from mapData
    };
});

OpenLayers 3 based on the Vector Icon Example

var latLon = ol.proj.transform([10.904108, 59.788187], 'EPSG:4326', 'EPSG:3857');

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

var iconStyle = new ol.style.Style({
    image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
        anchor: [0.5, 46],
        anchorXUnits: 'fraction',
        anchorYUnits: 'pixels',
        opacity: 0.75,
        src: 'imgs/lc.png'
    }))
});

iconFeature.setStyle(iconStyle);

var vectorSource = new ol.source.Vector({
    features: [iconFeature]
});

var vectorLayer = new ol.layer.Vector({
    source: vectorSource
});

var baseLayer = new ol.layer.Tile({
    source: new ol.source.OSM()
});

var view = new ol.View({
    center: latLon,
    zoom: 18,
});

var map = new ol.Map({
    target: 'map-canvas',
    layers: [ baseLayer, vectorLayer ],
    view: view
});

The changes are obviously not changing, but i know that magic does not exist it was just to put something down to start with.

How wouldi go forward accomplish this simple task? The only thing i want is the icon to update its position on the map when socket.io detects the new mapdata (mapData.lat, mapData.lon).

I have tried to dig into the different objects and read their properties both in the console and in the documentation, and i have searched here on Stackoverflow but sadly without luck. Do i hook into the iconFeature, or do i have to do this another way? Maybe something really easy is built in? Any help is much appreciated.

Upvotes: 1

Views: 3762

Answers (1)

Jonatas Walker
Jonatas Walker

Reputation: 14168

If you want to move an icon over the map, it's better you use an ol.Overlay for this. You can use marker.setPosition(coord) on each change.

A working fiddle. Click on map to change marker's position.

Upvotes: 1

Related Questions