I want to make the starting and ending vertex of an editable polyline non-editable. So that users can edit all other vertexes except those two. I have implemented an event listener (mousedown) to filter the vertex but how can I stop it from being editable.?
google.maps.event.addListener(poly, 'mousedown', function (event) {
if (event.vertex === 0) { // First vertex of polyline
//disable vertex from being editable
}
});
You're on the right path.
To detect a vertex has been moved, you listen to the set_at
event on the Polyline's Path. However, this won't let you know what was the original position, so what I'd do is capture the mousedown
event, just as you said, and declare an addListenerOnce
on the set_at
event of the Path to reset the vertex coords if I'm on the first or last point.
The following listener will allow the user to drag those vertices, but they'll subborntly go back to they original position:
google.maps.event.addListener(poly, 'mousedown', function (event) {
var thePath = this.getPath();
if (event.vertex === 0 || event.vertex === thePath.getLength() - 1) {
google.maps.event.addListenerOnce(thePath, 'set_at', function (vertex) {
this.setAt(vertex, event.latLng);
});
}
});
Why am I using addListenerOnce
? You see, that's because otherwise the very act of resetting the first or last points would trigger that same event, leading to an max stack error.
Edit: here's another shot at it. The following listener won't allow the user to drag said vertices. However, I'm re-enabling the editable behavior inmediatly. There might be a race condition in your browser.
google.maps.event.addListener(poly, 'mousedown', function (event) {
var thePath = this.getPath();
if (event.vertex === 0 || event.vertex === thePath.getLength() - 1) {
console.debug('Vertex forbidden!');
this.set('editable',false);
this.set('editable',true);
}
});