is there a correct way to move a single vertex programmatically in OpenLayers 2?

The problem is, I need to prevent users from drawing invalid (eg. self-crossing) polygons. To do that, I created a function to validate polygons, and then I validate the polygons in dragComplete method of OpenLayers.Control.ModifyFeature class (I created my own class based on this one).

Basically, I save current vertex position in dragStart method, then I validate the polygon in dragComplete method, and if the polygon is not valid, I change the coordinates of the vertex to the coordinates I've saved before.

It's working, the vertex moves back to the previous position. But there is a problem with dragging and rotation handlers. These handlers don't care that this vertex has been moved, they're positions are set to the center of the geometry with this wrong vertex (before it was moved). Both of these handlers come back to correct position when I drag or rotate the feature. I need them to be set correctly when this vertex is moved.

Is there some event or method I need to invoke to make it work correctly?

This is what I have put at the beginning of the dragComplete method.

dragComplete: function (vertex) {
    if (this.feature.geometry.isValid &&
        !this.feature.geometry.isValid()) {
        vertex.geometry.x = this.vertexPosition.x;
        vertex.geometry.y = this.vertexPosition.y;


It moves the vertex to given position correctly. The thing is it doesn't affect dragging handler and rotation handler. This is what I tried to use, without effect (it goes just below vertex.geometry.y = this.vertexPosition.y; in dragComplete method):

this.layer.events.triggerEvent('vertexmodified', {
    feature: this.feature,
    vertex: vertex
this.layer.events.triggerEvent('featuremodified', {
    feature: this.feature

None of this works. Is there a way to make these handlers refresh?


1 Answer 1


I managed to create a simple workaround - just invoked rotate method from the geometry object with zero as angle and center point as origin:

var bounds = this.feature.geometry.bounds;
var center = {
    x: bounds.left + (bounds.right - bounds.left) / 2,
    y: bounds.bottom + (bounds.top - bounds.bottom) / 2
this.feature.geometry.rotate(0, new OpenLayers.Geometry.Point(
    center.x, center.y

Maybe it's not a perfect way, but it's working :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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