Rinaldo Faria
Rinaldo Faria

Reputation: 31

How can I adjust the zoom on Open Layers for viewing all POI and Markers on the map

I need to show all POI and Markers in a Open Layers map with the best zoom defined. How can I get that?

I need the best zoom to show all markers on view.

Upvotes: 1

Views: 604

Answers (2)

Rinaldo Faria
Rinaldo Faria

Reputation: 31

            function setMapCenter() {
                var layers = multiMapa.getLayers();
                //that's it. It's started inverted to be adjusted on first iteration below.
                var minx = 9999999999;
                var miny = 9999999999;
                var maxx = -9999999999;
                var maxy = -9999999999;
                var extent = [];

                layers.forEach(function (lay) {
                    if (lay instanceof ol.layer.Vector) {
                        vehicleLayer = lay;
                        var features = lay.getSource().getFeatures();
                        features.forEach(function (fea) {
                            //all vectors, in this case, are Points.
                            var coords = String(fea.getGeometry().getExtent()).split(",");
                            if (minx > coords[0]) {
                                minx = coords[0];
                            }
                            if (miny > coords[1]) {
                                miny = coords[1];
                            }
                            if (maxx < coords[0]) {
                                maxx = coords[0];
                            }
                            if (maxy < coords[1]) {
                                maxy = coords[1];
                            }
                        });
                        //console.log(lay.getStyle().getText().getText());
                    }
                });
                console.log([minx, miny, maxx, maxy]);
                extent.push(minx);
                extent.push(miny);
                extent.push(maxx);
                extent.push(maxy);

                multiMapa.getView().fit(extent, multiMapa.getSize()); //[minx, miny, maxx, maxy]);
            }

Upvotes: 1

bahadrdsr
bahadrdsr

Reputation: 474

If all your features are on the same layer, get your vector's extent like;

const extent = yourLayer.getExtent();

Then do this;

 map.getView().fit(extent);

If they are on separate layers, you can either jam all of the features in a separate layer and get the extent that way or you can combine all of the features extents like this;

let featExtent = featuresOfInterest[0].getGeometry().getExtent();
for (let i = 0; i < featuresOfInterest.length; i++) { 
    ol.extent.extend(featExtent, featuresOfInterest[i].getGeometry().getExtent());
}

Then use the fit function of the view again like;

map.getView().fit(featExtent);

Upvotes: 0

Related Questions