DonMarco DonMarco - 2 years ago 158
Javascript Question

OL3: Zoom to vector layer on map

I have a map with openlayers 3 and a vector layer.
I want to map to be resized to this vector layer, but so far all I was able to get was to center the map on the last point of this vector, since the points of the vector layer are not accessible while creating the map:

if (trackMap != null) {
for (var i = 0; i < trackMap.length; i++) {
var trackInfo = trackMap[i];
lat = parseFloat(;
lon = parseFloat(trackInfo.lon);

var layergpx = new ol.layer.Vector({
source: new ol.source.Vector({
parser: new ol.parser.GPX(),
url: '${contextRoot}/gps/gpx2' + trackInfo.url

map = new ol.Map({
controls: ol.control.defaults().extend([
new ol.control.FullScreen()
layers: layers,
renderer: ol.RendererHint.CANVAS,
target: 'map',
view: new ol.View2D({
center: ol.proj.transform([lon, lat], 'EPSG:4326', 'EPSG:3857'),
zoom: 13

Answer Source

So... after a few days of testing and thinking I solved the problem. Not without further problems, but calculating the borders serverside and transmitting them to the script made it a bit easier.

The Javascript is fairly short for solving the problem:

if (minLon != null && minLat != null && maxLon != null && maxLat != null){
 var bottomLeft = ol.proj.transform([minLon, minLat], 'EPSG:4326', 'EPSG:3857');
 var topRight = ol.proj.transform([maxLon, maxLat], 'EPSG:4326', 'EPSG:3857');
 extent = new ol.extent.boundingExtent([bottomLeft,topRight]);
 map.getView().fitExtent(extent, map.getSize());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download