1

In Openlayers, I want on a single click on the map for a layer to be added and a feature to be dropped where I click.

vectorLayer = new OpenLayers.Layer.Vector("layer", {styleMap: currentStyle,'displayInLayerSwitcher': true});
map.addLayer(vectorLayer);
drawFeature = new OpenLayers.Control.DrawFeature(vectorLayer, OpenLayers.Handler.Point);
map.addControl(drawFeature);

I think this should probably be done with events somehow. But every option I try invovles a double click - one to add the layer, and one to add the feature. Anybody know how to solve this crisis? Thanks!

1 Answer 1

2

Only you need to do is to bind a OnClick event on the map and process what you want:

function bindClickButton() {
    OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {                
        defaultHandlerOptions: {
            'single': true,
            'double': false,
            'pixelTolerance': 0,
            'stopSingle': false,
            'stopDouble': false
        },

        initialize: function(options) {
            this.handlerOptions = OpenLayers.Util.extend(
                {}, this.defaultHandlerOptions
            );
            OpenLayers.Control.prototype.initialize.apply(
                this, arguments
            ); 
            this.handler = new OpenLayers.Handler.Click(
                this, {
                    'click': this.trigger
                }, this.handlerOptions
            );
        }, 

        trigger: function(e) {
            var lonlat = map.getLonLatFromPixel(e.xy);
            lonlat.transform( map.projection,map.displayProjection);
            processMouseClick(lonlat);
        }

    });

    var click = new OpenLayers.Control.Click();
    map.addControl(click);
    click.activate();

}

So, create the processMouseClick() to process the click :

function processMouseClick(lonlat) {
    // DO_ALL_YOUR_JOB_HERE
}

Just ignore my projection transform if not in your case.

2
  • Remember : var lon = lonlat.lon; var lat = lonlat.lat;
    – Magno C
    Jan 4, 2013 at 10:52
  • In your way, every click on map adds a new layer. Is this what you realy want? Be careful.
    – Magno C
    Jan 4, 2013 at 11:55

Your Answer

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

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