0

I click on the map on a polygon and I'd like to zoom the map and center it around the polygon.

We have done so until now:

map.on ('click', function (e) {
     console.log (s);
    // coordinate = evt.coordinate;
    
   

    var feature = map.forEachFeatureAtPixel (e.pixel, function (feature) {return feature;});

    var coordinate = e.coordinate;
    var hdms = ol.coordinate.toStringHDMS (ol.proj.transform (coordinate, 'EPSG: 31700', 'EPSG: 3857'));
    
    _myStroke = new ol.style.Stroke ({
       color: 'yellow',
       width: 4
    });
    
    _myFill = new ol.style.Fill ({
       color: 'rgba (255,0,0,1.0)'
    });
    
    selected_polygon_style = new ol.style.Style ({
       stroke: _myStroke,
       fill: _myFill
     });

   feature.setStyle (selected_polygon_style);
   
   map.fitBounds (e.layer.getBounds ());
)}

I'm trying to do this with this code line taken from an example here:

 map.fitBounds (e.layer.getBounds ());

But it is error:

Uncaught TypeError: Can not read property 'getBounds' of undefined

And I do not know what it could be.

  • 1
    fitBounds is used in Google maps. In OpenLayers to fit the map to your polygon use map.getView().fit(feature.getGeometry()); – Mike Mar 11 at 12:42
  • Yes running corectly, thanks Mike! – CoderCoder42 Mar 12 at 5:41
0

This sould do it:

map.getView().fit(feature.getGeometry())

You can also make it animated:

const fitOptions = {
    duration: 1000
}
map.getView().fit(feature.getGeometry(), fitOptions)

More info about the available options here: https://openlayers.org/en/latest/apidoc/module-ol_View.html#~FitOptions

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.