I tried all the day to zoom by default on my polygon 'geofield'. I'm using geoserver to store my data, I can display the map but the centre is in the middle of nowhere (I want it to be in the middle of the geofield). I tried something like this:
map.zoomToExtent(geofield.getDataExtent());
but it doesn't work! I also tried with a button like this:
var zoomToExtentControl = new ol.control.ZoomToExtent({
extent: [-11243808.051695308, 4406397.202710291,-4561377.290892059,6852382.107835932]});
it works when I clicked on it but when I try to replace the coordinates by geofield.geometry.getBounds()
the map doesn't display.
Here you can see the full code:
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="http://openlayers.org/en/v3.18.2/css/ol.css" type="text/css">
<style>
.map {
height: 400px;
width: 100%;
}
</style>
<script src="http://openlayers.org/en/v3.18.2/build/ol.js" type="text/javascript"></script>
<title>OpenLayers 3 example</title>
</head>
<body>
<h2>Weeds map test</h2>
<div id="map" class="map"></div>
<script type="text/javascript">
var zoomToExtentControl = new ol.control.ZoomToExtent({
extent: geofield.geometry.getBounds());
});
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
title: 'Global Imagery',
source: new ol.source.TileWMS({
url: 'http://demo.opengeo.org/geoserver/wms',
params: {LAYERS: 'nasa:bluemarble', VERSION: '1.1.1'}
})
}),
new ol.layer.Tile({
title: 'geofield',
source: new ol.source.TileWMS({
url: 'http://localhost:8080/geoserver/robot/wms',
params: {LAYERS: 'robot:geofield', VERSION: '1.1.1'}
})
}),
new ol.layer.Tile({
title: 'weeds',
source: new ol.source.TileWMS({
url: 'http://localhost:8080/geoserver/robot/wms',
params: {LAYERS: 'robot:weeds', VERSION: '1.1.1'}
})
}),
],
controls: ol.control.defaults().extend([
new ol.control.ScaleLine()]),
view: new ol.View({
center: ol.proj.fromLonLat([37.41, 8.82]),
zoom: 5
})
});
map.addControl(zoomToExtentControl);
</script>
</body>
</html>
Another thing; if you have a wms link for the world map (not satellite view) I'll need it!
Best Answer
Create your layers as variables outside the map to make them accessible:
In your map definition use your layer variables:
Then you can use
getExtent()
function on your layer (see API). Note that your functiongetDataExtent
does not exist...EDIT: Use this function to zoom to your extent: