首页 > 解决方案 > Mapbox-gl – rendering static map based on bounds?

问题描述

I have a Mapbox rendered in my browser, where the canvas is 400px wide and 300px tall (set using CSS). What I want to be able is to get a static representation of what I see in the screen using this mapbox API with the highest possible resolution, preserving the aspect ratio. I know that the maximum value passed to this API is 1280px hence the calculations:

const api_width = 1280;
const api_height = (300 * 1280) / 400;

I can get the centre of the map with the current zoom using MapBox API, but when I pass those values to the static map generator API, I get an image that's not properly adjusted (it's probably about the zoom).

How can I make sure that the static image I generate from the API looks exactly the same as what I see on the screen in my browser (with different canvas size)?

I thought about retrieving my map's bounds using getBounds method, but what should I do to recalculate those north-east and south-west bounds to pass the values to the static api?

My canvas: enter image description here Static API resut: enter image description here

I've also found this API now and passed my center lat and lng along with my zoom and current canvas dimensions to the .bounds() method. Then I grabbed the output and passed the bounds to the .viewport(). The results were passed to the static API and I got something that's pretty close, but it's not perfect:

const { lat, lng } = map.getCenter();
const zoom = map.getZoom();
const bounds = MapBoxGeo.bounds([lng, lat], zoom, [400, 300);
const viewport = MapBoxGeo.viewport(bounds, [1280, 960]);

enter image description here

The center and zoom values I get from my browser's map are:

const lat = 40.710590956829776;
​const lng = -74.00707253662097;
const zoom = 13.064434392733872

标签: javascriptmapboxmapbox-gl-js

解决方案


推荐阅读