Openlayers 3 map contextmenu

DDan picture DDan · Aug 26, 2015 · Viewed 7.2k times · Source

I would like to have a right-click context menu with the information of the point clicked.

I.e. I right click on map, get a dropdown menu, here if I would pick 'add marker' or similar, I need to have the clicked position.

I think simplest for getting the version right would be, if someone could add a simple drpdown menu on rightclick to this Test Fiddle

var map = new ol.Map({
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM()
    })
  ],
  target: 'map',
  controls: ol.control.defaults({
    attributionOptions: /** @type {olx.control.AttributionOptions} */ ({
      collapsible: false
    })
  }),
  view: new ol.View({
    center: [0, 0],
    zoom: 2
  })
});

I've seen this solution, but it didn't work out: https://gis.stackexchange.com/questions/148428/how-can-i-select-a-feature-in-openlayers-3-by-right-click-it

Answer

Jonatas Walker picture Jonatas Walker · Aug 27, 2015

UPDATE:

Now you can listen to some (two, for now) events. For example, if you want to make some conditionals and change menu items before the menu opens:

contextmenu.on('open', function(evt){
  var feature = map.forEachFeatureAtPixel(evt.pixel, function(ft, l){
    return ft;
  });

  // there's a feature at this pixel and I want to add
  // an option to remove this feature (marker)
  if (feature && feature.get('type') == 'removable') {

    // remove all items
    contextmenu.clear();

    // removeMarkerItem {Array}
    // propagate custom data to your callback
    removeMarkerItem.data = {
      marker: feature
    };

    contextmenu.push(removeMarkerItem);

  } else {
    contextmenu.clear();
    contextmenu.extend(contextmenu_items);
    contextmenu.extend(contextmenu.getDefaultItems());
  }
});

http://jsfiddle.net/jonataswalker/ooxs1w5d/


I just released the first version of a Custom Context Menu extension for Openlayers 3. It is like that for Leaflet. It is a ol.control.Control extended, so you add it to the map like:

var contextmenu = new ContextMenu();
map.addControl(contextmenu);

If you want some more items (there are some defaults):

var contextmenu = new ContextMenu({
    width: 170,
    default_items: true,
    items: [
        {
            text: 'Center map here',
            callback: center
        },
        {
            text: 'Add a Marker',
            icon: 'img/marker.png',
            callback: marker
        },
        '-' // this is a separator
    ]
});
map.addControl(contextmenu);

Demo Fiddle. Contributions are welcome.