danvk
danvk

Reputation: 16955

Equivalent of map.cameraForBounds without a Mapbox GL Map instance

With Mapbox GL JS, I can get a center and zoom level to show all of a given bounding box using the cameraForBounds method:

const {center, zoom} = map.cameraForBounds(
  [
    [sw.lng, sw.lat],
    [ne.lng, ne.lat],
  ],
  {
    padding: 20,
    bearing,
    pitch,  // probably ignored?
  },
);

(The typings say that pitch is OK but the docs don't mention it and neither does the implementation, so I assume it's ignored.)

This usually works great, but there occasionally situations where I want to figure out the center/zoom before the map is initialized. It seems like the bounds → camera transformation should just be math, not requiring a Map instance.

How can I go from bounds and bearing (and ideally pitch) to a center/zoom that will include those bounds without an instance of a Mapbox GL map?

Upvotes: 1

Views: 548

Answers (1)

Steve Bennett
Steve Bennett

Reputation: 126445

You can't, for the simple reason that you don't know how many pixels this map will occupy. Setting a centre and zoom determines how much area (and which area) will be covered by each pixel in the middle of the map. The bigger the map DOM element is, the more area will be covered by the area within the map.

Upvotes: 0

Related Questions