Openlayers 3 map contextmenu
Asked Answered
O

3

6

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

Opium answered 26/8, 2015 at 3:58 Comment(2)
Just combine that solution with this!Hube
Thanks for the pointerOpium
H
8

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.

Hube answered 27/8, 2015 at 10:20 Comment(2)
I kind of implemented my own, but just as standalone javascript. I like this one better. Tomorrow I'll try to integrate and i might contribute. Thanks!Opium
Fiddle does not work, as the url for the external resources has been changed. Check this instead: jsfiddle.net/04hhrqL7Festschrift
O
3

I have a solution, where I create own context menu from <div> elements and position it to the mouse. The menuitems define onclick, and give position, so I can place marker, can start drawing area...

Is this an elegant solution? Is there a better way to do?

Updated Demo

// ...
map.getViewport().addEventListener('contextmenu', function (e) {
    e.preventDefault();
    openContextMenu(e.layerX, e.layerY);
});

function openContextMenu(x, y) {
    $('.contextMenu').remove();
    $('body').append('<div class="contextMenu" style=" top: ' + y + 'px; left:' + x + 'px;">' +
        '<div class="menuItem" onclick="handleContexMenuEvent(\'addMarker\', \'' + x + '\', \'' + y + '\');"> Add Marker </div>' +
        '<div class="menuItem" onclick="handleContexMenuEvent(\'addArea\', \'' + x + '\',  \'' + y + '\');"> Add Area </div>' +
        '</div>');
}

function handleContexMenuEvent(option, x, y) {
    $('.contextMenu').remove();
    var location = map.getCoordinateFromPixel([x, y]);

    if (option == 'addMarker') {
        var feature = new ol.Feature(
        new ol.geom.Point(location));
        feature.setStyle(iconStyle);
        vectorSource.addFeature(feature);
    } else if (option == 'addArea') {
        //...
    }
}

Updated Demo

Opium answered 27/8, 2015 at 3:52 Comment(2)
This fiddle fails to work for me. As it opens the menu to a fixed position. e.layerX and e.layerY should be used instead of e.x and e.y. Also Appending a new instance to DOM and hiding it every time is not very elegant.Festschrift
@SoonDead Thanks! It makes sense. I updated the example.Opium
S
0

For anyone trawling through these pages in 2020, OpenLayers now has a map.on('contextmenu', function) event handler

Suppuration answered 3/6, 2020 at 7:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.