Adjusting map boundaries to match the raster layer dimensions

I have been searching through numerous tutorials on using `fitbounds` with Mapbox, but I am still unable to understand how to center my map on a specific raster layer. I have a menu that switches between various older maps and I want the map to adjust accordingly each time.

Here's what I currently have. The variable `mapnumber` represents the string for my raster map.

var coordinates = map.getBounds(mapnumber);
var bounds = new mapboxgl.LngLatBounds(coordinates[0], coordinates[0]);
map.fitBounds({bounds});

The bounds are being captured correctly, however, I am encountering an issue when trying to use `fitbounds`. This is the error message:

lng_lat.js:97 Uncaught Error: `LngLatLike` argument must be specified 
as a LngLat instance, an object {lng: <lng>, lat: <lat>}, or an array 
of [<lng>, <lat>]

Answer №1

Oops! An error has occurred: LngLatLike argument must be a LngLat instance

It seems like there's an issue with how you're using mapboxgl.LngLatBounds. You should provide two LngLat instances instead of coordinates. The API documentation includes an example that demonstrates creating points for the southwest and northeast corners of your bounding box:

var sw = new mapboxgl.LngLat(-73.9876, 40.7661);
var ne = new mapboxgl.LngLat(-73.9397, 40.8002);
var llb = new mapboxgl.LngLatBounds(sw, ne);

After that, you can utilize map.fitBounds() with the bounding box

map.fitBounds(llb);

UPDATE: responding to additional query

how can I extract the two sets (sw and ne) from the raster?

You can employ the map.getSource() method. Provide the source ID of your raster layer, which will return an object containing a bounds property. Use this bounds property when calling map.fitBounds().

var bounds = map.getSource('mapbox://username.source-id').bounds;
map.fitBounds(bounds);

Here's a functional example: https://codepen.io/mapsam/pen/RZvyBQ

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporate anchor or data-filter into the URL for better functionality

Is there a way to set up a button in a menu that sorts items listed below it? For example, let's say the button is labeled "news". Using the data-filter attribute or another method of identification, can I navigate to a specific page with this button ...

Splitting Node.js Requests to Avoid "Request Entity Too Large" Error

Whenever I attempt to transmit a large Json object (which includes base64 images) over the network to my node js server, I encounter the following issue: Error: request entity too large I came across a potential solution on this link (an inquiry on Sta ...

Can the tooltip of an element be changed while the old tooltip is still visible without having to move the mouse away and then back again?

When I have an HTML anchor element with a tooltip that appears when the mouse is hovered over it, and then I use JavaScript to change the tooltip's text using element.title = "Another Tooltip", the new tooltip text does not immediately update visually ...

The correct way to create a Reaction Collection

I'm trying to set up an event where a user triggers a reaction with either a Check mark or X. However, I keep encountering an error that the function doesn't exist for the message object. I attempted to switch back to awaitReactions but it didn& ...

Working with ng-model on an array with multiple dimensions

Currently, I am working on storing data in AngularJS. My table consists of various sections, rows, and columns. In each field, there is a dropdown list with the options "O", "T" or "E". My goal is to store these values in an array format: [section][row][c ...

What is the best way to obtain the clicked ID when a user clicks on an element within

As a budding web developer, I've been working on a code snippet to dynamically load data into an iframe: $(document).ready(function () { function loadMaterials(type, query) { $.ajax({ type: 'GET', url: &ap ...

What causes the data to flicker between the old and new values when the state is updated in ReactJS?

Currently, I am developing a single-page application that fetches data from the Star Wars API. In the character section of the project, the goal is to display characters per page with the ability to navigate to the next or previous pages by clicking on but ...

Is it possible for me to nest a Firebase collection within another collection?

When gathering user information and favorite foods in a form, I'd like the favorite food data to be nested under the 'users' collection as Likes: const sendPosts = (e) => { e.preventDefault() db.collection("users").add({ ...

Utilizing AND Operators and Wildcards in WHERE Statements for Various Conditions

On my screen, there are three input fields for capturing user search criteria. These fields are not mandatory and the input values are used as parameters in the SQL WHERE clause. Here is an example: SELECT col1, col2, col3, col4 FROM table LEFT JOIN othe ...

Spinning pictures, resembling AJAX, within the Ruby on Rails framework

Currently, I am developing a website and looking to implement an image cycling feature, like a slideshow, that changes images while the user is actively on the page. Despite looking extensively, I have yet to come across any useful information on how to do ...

Presenting JSON data in a table format on-the-fly even without prior knowledge of the data's structure or field names

When working with my application, I will be receiving data in JSON format and I am looking to showcase this data in a tabular form within a web browser. It's important to mention that I won't know beforehand the structure or field names of the re ...

Elements on the page are quivering as a result of the CSS animation

When a user clicks anywhere on a div, I have added a ripple effect to give it some interaction. However, there is an issue where the element shakes and becomes blurry when the page is in full screen mode until the ripple effect disappears. Below is the Ja ...

HTML/PHP/JS - Submit Form and Upload File Simultaneously

I need to create a form with a Photo Upload Input that allows users to upload pictures before submitting the form for faster processing. The form should also support uploading multiple files, display a progress bar, and provide a preview of the uploaded im ...

Restricting the number of lines within a paragraph in Angular 2

Is there a method to limit the number of lines in a <p> tag and add an ellipsis (...) at the end? Using character count for truncation doesn't work well as the width of the element varies according to device screen size. ...

"Exploring the process of transferring an ID from one service to another using the select feature in Angular

I need to store the ID I receive from one service into another using the select element. Here is my approach: <select class="form-control" id="select_fac" [(ngModel)]="rep.idfac"> <option selected disa ...

Can you share tips for passing a variable from a post request to a function that accepts parameters as a string or an array of strings in Node.js?

I am struggling to insert the variable named query into the end of the prompt. I attempted to use template literals but it was unsuccessful. (async () => { const gbtResponse = await openai.createCompletion({ model: "text-davinci-002", prompt ...

Guide on reusing javascript to toggle between image sources

I have a simple website with buttons that, when clicked, change the image being displayed. However, I find myself repeating code for each button, and I'm wondering if there is a more efficient solution to this problem. Here is an example of what I cu ...

Automatically switch/animate CSS classes at defined intervals using jQuery

In the PHP code snippet below, three list items are generated and a CSS class "active" is added/removed on mouseover/mouseout. The JavaScript provided toggles the "active" class for all list items at once when moused over, but the requirement is to anima ...

Issues arise with element binding when incorporating AngularJS UI-Router

My website utilizes AngularJS and UI-Router. To create a separate login page that is not injected into the main view, I decided to divide the index.html file into two parts: one with layout and script includes, and another with just script includes. This w ...

Include the name of the uploaded attachment in the textarea before hitting the submit button

Is there a way to automatically insert the filename into a textarea before the user submits the form? Can this be achieved using PHP or JavaScript? Thank you. <form id="Apply" name="Apply" method="post" enctype="multipart/form-data" action="applyLea ...