0

I want to create a snap control of my layer. My simple example demo is here

var raster = new ol.layer.Tile({
    source: new ol.source.OSM({       
    })
});

var source = new ol.source.Vector({
        format: new ol.format.GeoJSON(),
        url: 'https://raw.githubusercontent.com/openlayers/ol3/6838fdd4c94fe80f1a3c98ca92f84cf1454e232a/examples/data/geojson/countries.geojson'
    })

// vector layer
var vector = new ol.layer.Vector({
    source: source,
    style: new ol.style.Style({
        stroke: new ol.style.Stroke({
            color: '#eedd00',
            width: 1.5
        })
    })
});

// render the map    
var map = new ol.Map({
    target: 'map',
    renderer: 'canvas',
    layers: [raster, vector],
    view: new ol.View({
        center: [0, 0],
        zoom: 1
    })
});

var snap = new ol.interaction.Snap({
  source: source
});

map.addInteraction(snap);

snap.setActive(true);

I activated the snap interaction but it does not snap vectors

2

As per OpenLayers api doc

ol.interaction.Snap Handles snapping of vector features while modifying or drawing them

So you need to add a draw or modify interaction which when activated allows snap interaction to snap vectors

1

This answer aim is just to give an example, the @Johnson answer is correct and probably should be accepted.

You need to enable the modification or drawing interaction.

For example, to enable modifying interaction you can add these lines to your JS:

var modify = new ol.interaction.Modify({source:source});
map.addInteraction(modify);
modify.setActive(true);

After that you will be able to modify your source layer.

You can also have a look at this official example : https://openlayers.org/en/latest/examples/draw-and-modify-features.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.