Skip to content

Allow custom bearing/rotation while using fitBounds() #1338

Closed

Description

@friedbunny

The bearing option in fitBounds() is currently hard-coded to 0, but it would be nice to support eased rotation in fitBounds(), too. Removing that bearing = 0 line will rotate the map, but without easing and with uncorrected bounds.

Here's an test-case around Wyoming:

// Wyoming, slightly offset because of simplification
map.fitBounds([[45, -111],[41, -104]], { bearing: 45 });
// Draw Wyoming polygon
map.on('style.load', function() {
  map.addSource("wyoming", {
    "type": "geojson",
    "data": {"type":"FeatureCollection","features":[{"type":"Feature","properties":{},"geometry":{"type":"Polygon","coordinates":[[[-111,41],[-111,45],[-104,45],[-104,41],[-111,41]]]}}]}
  });

  map.addLayer({
    "id": "wyoming",
    "type": "fill",
    "source": "wyoming",
    "layout": {
    },
    "paint": {
      "fill-color": "blue",
      "fill-outline-color": "gray",
      "fill-opacity":  0.5
    }
  });
});

Which should ultimately end up like this:
screen shot 2015-06-25 at 1 49 36 pm

Activity

  1. 1ec5 commented on Jun 26, 2015

    @1ec5
    Contributor

    Dupe of #1225.

  2. kelvinabrokwa commented on Jun 26, 2015

    @kelvinabrokwa
    Contributor

    should be addresses in #1340

  3. 1ec5 commented on Jul 1, 2015

    @1ec5
    Contributor

    Reopening because #1340 has been pared down to just keep the bearing but not account for it.

  4. reopened this on Jul 1, 2015
  5. reopened this on Jul 1, 2015
  6. lucaswoj commented on Jul 28, 2016

    @lucaswoj
    Contributor

    Merged with #2112

  7. dagjomar commented on Sep 20, 2017

    @dagjomar
    Contributor

    Not sure what happened with this, but cannot find it in the actual mapbox-gl-js latest release.

    I ended up implementing my own version of fitBounds, called fitBoundsRotated, which has a small part of code that transforms the box and then uses that to calculate the ending bounds, plus using the map bearing or given bearing options.

    // Copied code from MapBoxGL's Camera#fitBounds method
    // Adding in rotation logic
    fitBoundsRotated( bounds, options, eventData ) {
    
            options = assign({
                padding: {
                    top: 0,
                    bottom: 0,
                    right: 0,
                    left: 0
                },
                offset: [0, 0],
                maxZoom: this.transform.maxZoom
            }, options);
    
            if (typeof options.padding === 'number') {
                const p = options.padding;
                options.padding = {
                    top: p,
                    bottom: p,
                    right: p,
                    left: p
                };
            }
    
            bounds = mapboxgl.LngLatBounds.convert(bounds);
    
            // we separate the passed padding option into two parts, the part that does not affect the map's center
            // (lateral and vertical padding), and the part that does (paddingOffset). We add the padding offset
            // to the options `offset` object where it can alter the map's center in the subsequent calls to
            // `easeTo` and `flyTo`.
            const paddingOffset = [options.padding.left - options.padding.right, options.padding.top - options.padding.bottom],
                lateralPadding = Math.min(options.padding.right, options.padding.left),
                verticalPadding = Math.min(options.padding.top, options.padding.bottom);
            options.offset = [options.offset[0] + paddingOffset[0], options.offset[1] + paddingOffset[1]];
    
            options.bearing = options.bearing || this.getBearing();
    
            const offset = mapboxgl.Point.convert(options.offset),
                tr = this.transform,
                nw = tr.project(bounds.getNorthWest()),
                se = tr.project(bounds.getSouthEast()),
            	size = se.sub(nw);
    
            	/** START CUSTOM ROTATION HACK **/
                // Now using a "cropped rectangle" rotation method
                // https://stackoverflow.com/questions/33866535/how-to-scale-a-rotated-rectangle-to-always-fit-another-rectangle
    	        // W = w·|cos φ| + h·|sin φ|
    	        // H = w·|sin φ| + h·|cos φ|
    	        const theta = options.bearing * (Math.PI/180),
    	        	W = size.x * Math.abs( Math.cos(theta) ) + size.y * Math.abs( Math.sin(theta) ),
    	        	H = size.x * Math.abs( Math.sin(theta) ) + size.y * Math.abs( Math.cos(theta) ),
    	        	rotatedSize = {x: W, y: H},
    	        /** END CUSTOM ROTATION HACK **/
    
                	scaleX = (tr.width - lateralPadding * 2 - Math.abs(offset.x) * 2) / rotatedSize.x,
                	scaleY = (tr.height - verticalPadding * 2 - Math.abs(offset.y) * 2) / rotatedSize.y;
    
            if (scaleY < 0 || scaleX < 0) {
            	if (typeof console !== "undefined") console.warn('Map cannot fit within canvas with the given bounds, padding, and/or offset.');
                return this;
            }
    
            options.center = tr.unproject(nw.add(se).div(2));
            options.zoom = Math.min(tr.scaleZoom(tr.scale * Math.min(scaleX, scaleY)), options.maxZoom);
    
    
            return options.linear ?
                this.easeTo(options, eventData) :
                this.flyTo(options, eventData);
    }
    
    

    Not sure if this could get reviewed and considered implemented. Pinging @lucaswoj just to let someone know.

  8. phonebooks commented on Apr 5, 2018

    @phonebooks

    Dagjomar - how do I get this function to work in my JS program ??
    this is exactly what I need by the way !! Thanks

  9. dagjomar commented on Jun 8, 2018

    @dagjomar
    Contributor

    @phonebooks in my code, I have my own class Map that extends mapbox-gl/map, and than this function is included there.

    Alternatively, I believe you could just have this function outside of your map, but when calling it you must bind the function to the map object so that this references will behave relative to the map itself

  10. sleep-drifter commented on Jul 3, 2018

    @sleep-drifter

    Would love to see this implemented. Thanks for the work around @dagjomar

  11. waissbluth commented on Apr 28, 2020

    @waissbluth

    Was a combination of uneven padding and bearing considered in the implementation? I opened an issue about that: #9641

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions