Reputation: 171
I'm using openlayers 6.5 and I want to set the center of the map and to fit all polygons drawned.
Here is what I have:
/*** Set the map ***/
var map = new ol.Map({
target: map_element,
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
view: new ol.View({
center: ol.proj.fromLonLat([
'24.6859325',
'45.9852429',
]),
zoom: 6
})
});
/*** Set counties polygon on the map ***/
for(var county_id in map_json_data)
{
map_json_data[county_id]['google_map_county_polygon'] = new ol.Feature({
geometry: new ol.geom.Polygon([map_json_data[county_id]['county_polygon_coordinates']])
});
map_json_data[county_id]['google_map_county_polygon'].getGeometry().transform('EPSG:4326', 'EPSG:3857');
map.addLayer(
new ol.layer.Vector({
source: new ol.source.Vector({
features: [ map_json_data[county_id]['google_map_county_polygon'] ]
})
})
);
}
/*** Here I want to set all polygons to be centered on the map and to fill the maximum zoom ***/
Some help based on code I have ?
Upvotes: 0
Views: 1665
Reputation: 17897
You could build up a combined extent as you add features and then fit the view to that
var extent = ol.extent.createEmpty();
/*** Set counties polygon on the map ***/
for(var county_id in map_json_data)
{
map_json_data[county_id]['google_map_county_polygon'] = new ol.Feature({
geometry: new ol.geom.Polygon([map_json_data[county_id]['county_polygon_coordinates']])
});
map_json_data[county_id]['google_map_county_polygon'].getGeometry().transform('EPSG:4326', 'EPSG:3857');
ol.extent.extend(extent, map_json_data[county_id]['google_map_county_polygon'].getGeometry().getExtent());
map.addLayer(
new ol.layer.Vector({
source: new ol.source.Vector({
features: [ map_json_data[county_id]['google_map_county_polygon'] ]
})
})
);
}
map.getView().fit(extent);
It could be made simpler if you are able to have all your polygons in a single vector layer
var vectorSource = new ol.source.Vector();
map.addLayer(
new ol.layer.Vector({
source: vectorSource
})
);
/*** Set counties polygon on the map ***/
for(var county_id in map_json_data)
{
map_json_data[county_id]['google_map_county_polygon'] = new ol.Feature({
geometry: new ol.geom.Polygon([map_json_data[county_id]['county_polygon_coordinates']])
});
map_json_data[county_id]['google_map_county_polygon'].getGeometry().transform('EPSG:4326', 'EPSG:3857');
vectorSource.addFeature( map_json_data[county_id]['google_map_county_polygon']);
}
map.getView().fit(vectorSource.getExtent());
Upvotes: 1