[GIS] How get map extents for drawn polygon when final click is done

ext-jsgeoextopenlayers-2

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?

Best Answer

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/