问题
Welcome and greetings!
How to get coordinates of features from snap function? I am using this example OpenLayers website: http://openlayers.org/en/latest/examples/snap.html?q=snap
I tried to do it this way:
snap.on('select', function(evt) {
var coord = evt.selected[0].getGeometry().getCoordinates();
alert(coord);
});
But is not working. I need to use 'select','drawend',modifyend' events.
回答1:
I had a hard time finding a solution to this myself but after debugging the ol code I came up with this solution.
When an event is created in ol all interactions are iterated from last to first. Snap interaction replace the pointer coordinate (if snapping) and all interactions coming before (after when iterating, since iterating backwards) will get this coordinate.
So either run your code in a custom interaction or use a custom interaction to exctract the coordinate, like this example in TypeScript:
let snapCoordinate: ol.Coordinate;
let getSnapCoordinateInteraction = new ol.interaction.Interaction({
handleEvent: (evt: ol.MapBrowserEvent) => {
snapCoordinate = evt.coordinate;
return true;
}
});
this.map.addInteraction(getSnapCoordinateInteraction);
// Snap, should always be last of all interactions that should use the snap coordinate.
this.snap = new ol.interaction.Snap({
source: this.source,
});
this.map.addInteraction(this.snap);
来源:https://stackoverflow.com/questions/43813089/get-coordinates-from-snap-in-openlayers