Curious
Curious

Reputation: 401

OpenLayers 6 BBOX to extent

I wonder if there is an easy way to transform a BBOX returned from an API call :

{
"title": "031G05 OTTAWA",
"qualifier": "LOCATION",
"type": "ca.gc.nrcan.geoloc.data.model.NTS",
"bbox": [-76.0, 45.25, -75.5, 45.5],
"geometry": {"type":"Point","coordinates":[-75.75,45.375]}
}

can be transformed to an extent that can be passed to a map.getView().fit(extent) call. Is there a simple OpenLayers API way of achieving this?

Upvotes: 0

Views: 1360

Answers (1)

geocodezip
geocodezip

Reputation: 161334

Assuming those coordinates are ESPG:4326, and your map view projection is EPSG:3857:

var jsonData = {
  "title": "031G05 OTTAWA",
  "qualifier": "LOCATION",
  "type": "ca.gc.nrcan.geoloc.data.model.NTS",
  "bbox": [-76.0, 45.25, -75.5, 45.5],
  "geometry": {"type":"Point","coordinates":[-75.75,45.375]}
}
// transform bbox from EPSG:4326 to EPSG:3857
const extent = ol.proj.transformExtent(jsonData.bbox, 'EPSG:4326', 'EPSG:3857');

map.getView().fit(extent);

proof of concept

enter image description here

code snippet:

var map = new ol.Map({
  layers: [
    new ol.layer.Tile({ // TileLayer({
      source: new ol.source.OSM()
    })
  ],
  target: 'map',
  view: new ol.View({
    center: [0, 0],
    zoom: 2
  })
});
var jsonData = {
  "title": "031G05 OTTAWA",
  "qualifier": "LOCATION",
  "type": "ca.gc.nrcan.geoloc.data.model.NTS",
  "bbox": [-76.0, 45.25, -75.5, 45.5],
  "geometry": {
    "type": "Point",
    "coordinates": [-75.75, 45.375]
  }
}
// transform bbox from EPSG:4326 to EPSG:3857
const extent = ol.proj.transformExtent(jsonData.bbox, 'EPSG:4326', 'EPSG:3857');

map.getView().fit(extent);
html,
body {
  height: 100%;
  width: 100%;
  padding: 0px;
  margin: 0px;
}

.map {
  height: 95%;
  width: 100%;
}
<!DOCTYPE html>
<html>

<head>
  <title>Simple Map</title>
  <link rel="stylesheet" href="https://openlayers.org/en/v6.14.1/css/ol.css" type="text/css">
  <!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
  <script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
  <script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.14.1/build/ol.js"></script>
</head>

<body>
  <div id="map" class="map"></div>
</body>

</html>

Upvotes: 2

Related Questions