mapbox-gl: calculate map bounds from center point,

2019-07-16 10:20发布

问题:

Using mapbox-gl-native in Node.js I need to find out the actual bounds of a map after rendering. I'm rendering a map as outlined in the project's README.md:

var fs = require('fs');
var path = require('path');
var mbgl = require('mapbox-gl-native');
var sharp = require('sharp');

var options = {
    request: function(req, callback) {
        fs.readFile(path.join(__dirname, 'test', req.url), function(err, data) {
            callback(err, { data: data });
        });
    },
    ratio: 1
};

var map = new mbgl.Map(options);

map.load(require('./test/fixtures/style.json'));

map.render({zoom: 12.25, center: [-122.67, 45.52]}, function(err, buffer) {
    if (err) throw err;

    // TODO: get map extent
    // var extent = map.extent(); 
    // extent is {minX: ..., maxX: ..., minY: ..., maxY: ...} or similar...

    map.release();

    var image = sharp(buffer, {
        raw: {
            width: 512,
            height: 512,
            channels: 4
        }
    });

    // Convert raw image buffer to PNG
    image.toFile('image.png', function(err) {
        if (err) throw err;
    });
});

After the map is rendered, I would like to find out what the bounds of the rendered map are. Does anyone know if this is possible with mapbox-gl-native or if this is something that could be added to the API in a future version? Or is there another way to calculate the actual bounds of a map simply from the zoom level, the map's center and the map's dimensions?

I used and slightly adjusted the excellent answer by @JohnS to a similar question to calculate the zoom level from a given extent. Maybe there is a way to revert this calculation to obtain the actual extent?

回答1:

I think you can try mapbox/geo-viewport:

geoViewport.bounds([-122.67, 45.52], 12.25, [512, 512])