Search code examples
openlayers

How to update marker location on click?


I followed this example to create a simple map with a circle marker point on it: https://openlayers.org/en/latest/examples/icon-color.html

This is my current code:

import Feature from 'ol/Feature.js';
import Map from 'ol/Map.js';
import Point from 'ol/geom/Point.js';
import View from 'ol/View.js';
import {Icon, Style} from 'ol/style.js';
import {OSM, Vector as VectorSource} from 'ol/source.js';
import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer.js';
import {fromLonLat} from 'ol/proj.js';

const rome = new Feature({
  geometry: new Point(fromLonLat([12.5, 41.9])),
});

rome.setStyle(
  new Style({
    image: new Icon({
      color: '#BADA55',
      crossOrigin: 'anonymous',
      src: 'data/dot.svg',
    }),
  }),
);

const vectorSource = new VectorSource({
  features: [rome],
});

const vectorLayer = new VectorLayer({
  source: vectorSource,
});

const tileLayer = new TileLayer({
  source: new OSM()
});

const map = new Map({
  layers: [tileLayer, vectorLayer],
  target: document.getElementById('map'),
  view: new View({
    center: fromLonLat([2.896372, 44.6024]),
    zoom: 3,
  }),
});

And now I want to be able to click on the dot and change it's position to a new point given a new longitude and latitude.

I've looked in the docs for Point: https://openlayers.org/en/latest/apidoc/module-ol_geom_Point-Point.html

But they are really confusing, and I could not find the way to make the above point clickable and moved to a new location (in this case I just want to move it to a nearby location given a fixed longitude and latitude)

The docs are just really confusing


Solution

  • You need to listen for click events on the map and let OpenLayers find any features at that location.

    map.on('singleclick', function (e) {
      map.forEachFeatureAtPixel(e.pixel, function (f) {
        if (f === rome) {
          f.getGeometry().setCoordinates(fromLonLat([28.9744, 41.0128]))
        }
      });
    });
    

    If the feature is Rome it will move to Istanbul.