Merge pull request #102 from uber/add-fitbounds

Add fitBounds
This commit is contained in:
Ib Green 2016-07-28 15:44:21 -07:00 committed by GitHub
commit cfecf08b25
2 changed files with 29 additions and 0 deletions

27
src/fit-bounds.js Normal file
View File

@ -0,0 +1,27 @@
// NOTE: Transform is not a public API so we should be careful to always lock
// down mapbox-gl to a specific major, minor, and patch version.
import Transform from 'mapbox-gl/js/geo/transform';
import {LngLatBounds, Point} from 'mapbox-gl';
export default function fitBounds(width, height, _bounds, options) {
const bounds = new LngLatBounds([_bounds[0].reverse(), _bounds[1].reverse()]);
options = options || {};
const padding = typeof options.padding === 'undefined' ? 0 : options.padding;
const offset = Point.convert([0, 0]);
const tr = new Transform();
tr.width = width;
tr.height = height;
const nw = tr.project(bounds.getNorthWest());
const se = tr.project(bounds.getSouthEast());
const size = se.sub(nw);
const scaleX = (tr.width - padding * 2 - Math.abs(offset.x) * 2) / size.x;
const scaleY = (tr.height - padding * 2 - Math.abs(offset.y) * 2) / size.y;
const center = tr.unproject(nw.add(se).div(2));
const zoom = tr.scaleZoom(tr.scale * Math.min(scaleX, scaleY));
return {
latitude: center.lat,
longitude: center.lng,
zoom
};
}

View File

@ -20,6 +20,8 @@
import MapGL from './map.react';
import * as overlays from './overlays';
import fitBounds from './fit-bounds';
module.exports = MapGL;
module.exports.fitBounds = fitBounds;
Object.assign(module.exports, overlays);