Georg Schölly Georg Schölly - 5 months ago 46
Javascript Question

How to add clickable margins around an icon in openlayers 3?

I'm using openlayers 3 to show a map with some markers that have a small icon. Upon clicking one of them, the browser switches to another page associated with the marker.

The markers are currently implemented as features:

const style = new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 1.0],
anchorXUnits: 'fraction',
anchorYUnits: 'fraction',
src: img_url,
})
});

const feature = new ol.Feature({
geometry: new ol.geom.Point([x, y]),
});

feature.setStyle(style);


Here's my click handler:

map.on("click", e => {
map.forEachFeatureAtPixel(e.pixel, (feature) => {
window.location.href = "/s/" + feature.getId();
return true; // stop after first feature
});
});


Unfortunately, the icons are quite small and therefore hard to hit on a touch-based interface such as an iPad.

Is there an accepted way of making the target larger? My ideas are the following:


  • Create an additional invisible marker for each marker and make those clickable.

  • Instead of only using the event's location, I could sample some pixels around it and use all features nearby.



Is there a better way to do this?

Answer

My suggestion is that you create an invisible square around your icon like:

const style = [
  new ol.style.Style({
    image: new ol.style.Icon({
      anchor: [0.5, 1.0],
      anchorXUnits: 'fraction',
      anchorYUnits: 'fraction',
      src: img_url,
    })
  }),
  new ol.style.Style({
    image: new ol.style.RegularShape({
      stroke: new ol.style.Stroke({ color: [0, 0, 0, 0] }),
      points: 4,
      radius: 50, // <--------- control its size
      angle: Math.PI / 4
    })
  })
];
Comments