0

I am using OpenLayers JS to draw a polygon and now I want map extents of the drawn polygon one final click (i.e. user finish drawing polygon or double click is done). For drawing the polygon I am using following code:

action = Ext.create('GeoExt.Action', {
        text: "Draw Poly",
        icon: 'Images/poly.png',
        control: new OpenLayers.Control.DrawFeature(
            vector, OpenLayers.Handler.Polygon
        ),
        map: map,
        // button options
        toggleGroup: "draw",
        allowDepress: false,
        tooltip: "Draw Polygon",
        // check item options
        group: "draw"
    });

This code is written using OpenLayers JS, Ext JS and GeoExt JS.

Can anyone please tell me how to get map extents for the drawn polygon?

2
  • Do you want the extent, after the user has drawn the polygon? have you looked at the Polygon.getBounds() function? Apr 26, 2013 at 5:49
  • yes i want the polygon extends after user finish drawing. i have to do once user finish drawing in this case Polygon.getBounds() will help? how please guide me or give sample reference.
    – Pari
    Apr 26, 2013 at 5:53

1 Answer 1

2

You need to listen to the featureadded event of the vector layer, and then get the geometry there.

Have a look at the following JavaScript code:

var map;
function init(){
    map = new OpenLayers.Map('map');

    var wmsLayer = new OpenLayers.Layer.WMS( "OpenLayers WMS",
        "http://vmap0.tiles.osgeo.org/wms/vmap0?", {layers: 'basic'});

    var polygonLayer = new OpenLayers.Layer.Vector("Polygon Layer");

    map.addLayers([wmsLayer,polygonLayer]);
    map.addControl(new OpenLayers.Control.MousePosition());

   var  polygon= new OpenLayers.Control.DrawFeature(polygonLayer,OpenLayers.Handler.Polygon);

    map.addControl(polygon);


    map.setCenter(new OpenLayers.LonLat(0, 0), 3);

    //activate the control
    polygon.activate();

    //register the event listner
    polygonLayer.events.register('featureadded',polygonLayer, onAdded);
}

function onAdded(ev){
    var polygon=ev.feature.geometry;
    var bounds=polygon.getBounds();
    //now do whatever you want with the bounds
    //I'm just logging it to the console                
    console.log(bounds);
}

You can also see this working example: http://jsfiddle.net/devdatta/sFaag/

3
  • Thanks for this, but how i will use using openlayer js , extjs and geoext js. please see my code for that.
    – Pari
    Apr 26, 2013 at 6:36
  • You have a vector layer called 'vector', right? Then just call vector.events.register('featureadded',vector, onAdded); and add the required onAdded function somewhere in your js file. Apr 26, 2013 at 6:38
  • sorry for that. please see if accepted is checked now
    – Pari
    Apr 26, 2013 at 7:13

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.