OpenLayers 6 BBOX 扩展

OpenLayers 6 BBOX to extent

我想知道是否有一种简单的方法来转换从 API 调用返回的 BBOX :

{
"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]}
}

可以转换到可以传递给 map.getView().fit(extent) 调用的范围。有没有一种简单的 OpenLayers API 方法可以实现这一点?

假设这些坐标是 ESPG:4326,并且您的地图视图投影是 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

代码片段:

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>