Fitting map bounds to raster layer

巧了我就是萌 提交于 2019-12-12 04:07:10

问题


I've ran across all fitbounds tutorials for Mapbox and still cannot figure out how refocus my map on a given raster layer. I have a menu that toggles a number of older maps and would like to refit the map at each turn.

Here's what I have so far. mapnumber is the string for my raster map.

      var coordinates = map.getBounds(mapnumber);
      var bounds = new mapboxgl.LngLatBounds(coordinates[0], coordinates[0]);
      map.fitBounds({bounds});

The bounds are there, I just cannot use fitbounds on them. This is the error.

lng_lat.js:97 Uncaught Error: `LngLatLike` argument must be specified 
as a LngLat instance, an object {lng: <lng>, lat: <lat>}, or an array 
of [<lng>, <lat>]

回答1:


Uncaught Error: LngLatLike argument must be specified as a LngLat instance

It looks like you're using mapboxgl.LngLatBounds incorrectly. You'll need to pass in two LngLat instances, rather than two coordinates. The API docs have an example that creates a point for the southwest and northeast corners of your bounding box:

var sw = new mapboxgl.LngLat(-73.9876, 40.7661);
var ne = new mapboxgl.LngLat(-73.9397, 40.8002);
var llb = new mapboxgl.LngLatBounds(sw, ne);

Then you can use map.fitBounds() with the bounding box

map.fitBounds(llb);

UPDATE: answering follow up question

how can I extract the two sets (sw and ne) from the raster?

You can use the map.getSource() method. Pass in the source ID of your raster layer and that will return an object that has a bounds property. Use this bounds property to pass into map.fitBounds().

var bounds = map.getSource('mapbox://username.source-id').bounds;
map.fitBounds(bounds);

Here's a working example: https://codepen.io/mapsam/pen/RZvyBQ



来源:https://stackoverflow.com/questions/45997911/fitting-map-bounds-to-raster-layer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!