Skip to main content
Question is about OL3 not OL2 (tag synonym probably included it by mistake)
Link
Evil Genius
  • 6.3k
  • 2
  • 28
  • 40
Source Link
Luke
  • 41
  • 1
  • 5

Parse WKT and zoom to polygon extent using openlayers

I'm having trouble getting Openlayers to zoom to a polygon extent using "map.zoomToExtent(vector.getDataExtent());" The object parsed as WKT loads and displays fine but I want to zoom to the polygon extent. I have a bunch of these to do, so manually setting it is not an option.

This is an adaptation of the standard WKT parsing example.

<!DOCTYPE html>
<html>
<head>
<title>WKT example</title>
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ol3/3.6.0/ol.css" type="text/css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/ol3/3.6.0/ol.js"></script>

</head>
<body>
<div class="container-fluid">

<div class="row-fluid">
  <div class="span12">
    <div id="map" class="map"></div>
  </div>
</div>

</div>
<script>

var raster = new ol.layer.Tile({
  source: new ol.source.OSM()
});

var format = new ol.format.WKT();
var feature = format.readFeature(
    'POLYGON ((168.15376629900004 -46.965902961999973,168.15425575900008 -46.960042994999981,168.157709620000105 -46.923741522999933,168.163779654000109 -46.920341960999963,168.164207980000015 -46.920102451999981,168.172069460000102 -46.915702541999963,168.181400489000112 -46.91607862799998,168.204876069000079 -46.917021440999974,168.204698190000045 -46.918875067999977,168.200562607000052 -46.961988580999957,168.199261413000045 -46.979633681999985,168.190036795000083 -46.979308838999941,168.152751593000062 -46.977995387999954,168.15376629900004 -46.965902961999973))');
feature.getGeometry().transform('EPSG:4326', 'EPSG:3857');

var vector = new ol.layer.Vector({
  source: new ol.source.Vector({
    features: [feature]
  })
});

var map = new ol.Map({
  layers: [raster, vector],
  target: 'map',
  view: new ol.View({
    center: ol.proj.transform([168, -46.97], 'EPSG:4326', 'EPSG:3857'),
    zoom: 11
  })
});

map.zoomToExtent(vector.getDataExtent());

</script>

</body>
</html>