ThriceGood
ThriceGood

Reputation: 1703

OpenLayers4: How to give icon a bigger click radius

I am trying to make an Icon feature that I can click on easier on mobile phones. I have an icon set up nicely and when using a mouse to click on it there is no issue. However when using my finger or thumb on a mobile phone it is quite difficult to get an accurate click. I am using a ol.geom.Point and giving it an icon style. I tried an ol.geom.Circle but I can't get the icon style to work with it.

Here is an example of my working ol.geom.Point:

        for (i in spots) {
            var spot = spots[i];
            var coords = spot['coords'];
            var lat = parseFloat(coords.split(',')[0]);
            var lng = parseFloat(coords.split(',')[1]);
            var iconFeature = new ol.Feature({
                geometry: new ol.geom.Point(ol.proj.fromLonLat([lng, lat])),
                type: 'spot'
            });  
            iconFeature.setStyle(spotMarker);
            features.push(iconFeature);
        }
        vectorSourceSpots = new ol.source.Vector({
            features: features
        });
        var vectorLayer = new ol.layer.Vector({
            source: vectorSourceSpots
        });
        map.addLayer(vectorLayer); 

Here is the spotMarker style:

        var spotMarker = new ol.style.Style({
            image: new ol.style.Icon(({
                src: 'images/spot.png'
            }))
        });

I've also tried with a ol.geom.Circle but I could not see my icon when I tried this:

        for (i in spots) {
            var spot = spots[i];
            var coords = spot['coords'];
            var lat = parseFloat(coords.split(',')[0]);
            var lng = parseFloat(coords.split(',')[1]);
            var iconFeature = new ol.Feature({
                geometry: new ol.geom.Circle(ol.proj.fromLonLat([lng, lat]), 5),
                type: 'spot'
            });  
            iconFeature.setStyle(spotMarker);
            features.push(iconFeature);
        }
        vectorSourceSpots = new ol.source.Vector({
            features: features
        });
        var vectorLayer = new ol.layer.Vector({
            source: vectorSourceSpots
        });
        map.addLayer(vectorLayer); 

What I want is to have the icon remain the same size, but just to increase the click radius around the icon. Almost like an invisible circle a bit bigger than the icon with the same center.

Is this possible?

Upvotes: 1

Views: 528

Answers (1)

Chase Choi
Chase Choi

Reputation: 1012

You will use forEachFeatureAtPixel to add event on the features, then you can set hitTolerance on its options parameter.

check this api document: forEachFeatureAtPixel

you may need to write:

var addEvent = function(map, evt) {
    map.forEachFeatureAtPixel(evt.pixel, function(feature, layer) {

    }, {
        hitTolerance: 10
    });
};

map.on('click', function(evt) {
    addEvent(map, evt);
});

Upvotes: 1

Related Questions