Utilizing Mapbox GL JS: Incorporating a canvas for weather mapping and extracting information from it

Two issues have caught my attention recently, and I find myself delving into research to understand them better.

The first one revolves around the mysterious process of adding a canvas to my map. Despite my efforts, I can't seem to find a straightforward example that works efficiently. I've explored the Mapbox API documentation at this link, but it doesn't provide a clear demonstration like an image overlay does.

While the API outlines how to add a canvas source, there's a lack of guidance on displaying it on the map. Am I overlooking something in the instructions, or is this aspect simply missing? A working example of an image source would be helpful for comparison purposes.

My current project involves showcasing weather radar data. Once I crack the code on incorporating a canvas source and displaying it properly, my next objective is to create tooltips that reveal data values upon hovering over specific areas. Each color on the canvas corresponds to a precise numerical value, making it easier for users to interpret the information (e.g., #63C2FF = 15.4, #469B00 = 23.4, #FDF900 = 31.5, etc).

Is it feasible to implement these interactive features using MapBox GL JS? While online sources suggest utilizing a canvas, practical examples are scarce. Even a simple code snippet representing a 10px by 10px image with just two colors would go a long way in helping me grasp the concept. Although I anticipate challenges such as image refreshment, I feel confident about troubleshooting those once I overcome the initial hurdle.

Below is functional code for an image overlay that I currently employ successfully. Could a canvas exhibit similar behavior within this framework?

map.on('load', function() {
  map.addSource("source_KEWX_L2_REFLECTIVITY", {
    "type": "image",
    "url": "images/KEWX_L2_REFLECTIVITY.gif",
    "coordinates": [
      [-103.009641, 33.911],
      [-94.009641, 33.911],
      [-94.009641, 24.911],
      [-103.009641, 24.911]
    ]
  })
  map.addLayer({
    "id": "overlay_KEWX_L2_REFLECTIVITY",
    "source": "source_KEWX_L2_REFLECTIVITY",
    "type": "raster",
    "raster-opacity": 0.5,
    "layout": {
      "visibility": "none"
    },
  })
});

Lastly, envisioning how this functionality should ideally operate, I aspire to achieve results akin to the following example image:

https://i.sstatic.net/LalFU.jpg

Answer №1

Indeed, the documentation lacks detailed information about the canvas source type. However, you can refer to this link for some mention of it:

Typically, a canvas source is used similarly to an image source, which means selecting a raster layer to display it on the map.

Retrieving Color Values

To retrieve the color values from the canvas content, you can utilize the getImageData method of the context:

const context = canvas.getContext('2d');
const imageData = context.getImageData(0, 0, canvas.width, canvas.height);

You can access the colors from the imageData.data property. This will provide a flat (1-dimensional) array of colors in RGBA order. For example, in a 4x4px image, the array may appear as follows:

[
  r0, g0, b0, a0, // pixel [0, 0]
  r1, g1, b1, a1, // pixel [1, 0]
  r2, g2, b2, a2, // pixel [0, 1]
  r3, g3, b3, a3  // pixel [1, 1]
]

The values range from 0 to 255.

To incorporate this, capture the mousemove event on the map, obtain the lng/lat position of the cursor, convert this into an x/y position for accessing the correct pixel in the image data.

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

Looking for reliable resources on establishing a connection between a Google account and my application

I am currently working on creating a react native app that aims to simplify the user login process by allowing them to link their Google account with just one click. This way, users won't have to constantly log in every time they use the app. While I ...

The Vue.js instance is referencing the "options" property or method during render, but it has not been defined

Working with Vue.js (and Inertia.js), I encountered an issue while trying to build a select element in my form. After compiling, the select appears empty, and the developer console in the web browser shows the following error: The property or method "opti ...

Working on rectifying the Chat Engine API code that was causing a 403 Status Code to be generated

Encountering a status code 403 while attempting to create a chat engine IO page, even though all authentication headers are believed to be accurate. Double-checked for typos but still unable to identify the issue. Despite console logging the user correctly ...

Optimal method for efficiently loading a JSON file over 100MB in Node.js

Each day, my system generates data and stores it in a json file that is around 120MB in size. I'm currently working on sending this data to the client using nodejs. router.get('/getData',(req, res) => { const newData = require(`./ne ...

Axios - retrieving merchandise

I have created an endpoint that retrieves all product information in JSON format. I am attempting to display this data on my index.html page using Axios, but I am encountering difficulties with getting the data correctly. This is my first time working with ...

Chat Bot - EmbedMessage

JavaScript is still very new to me and I find the actual code quite challenging to grasp. However, I do have one specific question - how can I display the "cahbResponses" in a MessageEmbed? Despite consulting the Discord JS guides on MessageEmbeds, I' ...

Facing an issue where WordPress AJAX is not showing the expected content

Currently, I am in the process of creating a WordPress website that will feature an initial display of two rows of images. Upon clicking a button, two more rows should dynamically appear. There are four key files involved in this project: case-study-ca ...

Exploring the use of Angular with tables: applying classes dynamically using ngClass and repeating items using

My table is generated from a Web Service JSON, each row has a button to mark it for deletion. When you click the button, a JS alert displays the ID of the row element, and I also need to add the 'danger' bootstrap class to the row. Now, I can cap ...

Executing the executeScript method in Microsoft Edge using Java and WebDriverWould you like a different version?

I'm currently attempting to execute the following code in Microsoft Edge using WebDriver ExpectedCondition<Boolean> jsLoad = driver -> ((JavascriptExecutor) driver).executeScript("return document.readyState").toString().equals(&quo ...

Accessing external server with AJAX

I'm attempting to fetch a cross-domain HTML page through AJAX, but I'm running into an issue where I can only receive a response if the dataType is set to "jsonp". However, when using jsonp, the browser expects a script mime type but receives "te ...

JavaScript: Struggling to send new data to mongodb REST API via POST request

After spending time developing a REST API that displays information about the planets in our solar system on a local server in .JSON format, I encountered an issue with POST requests. Although GET requests were successful when testing the URL (localhost:80 ...

Issue with moment library causing date to appear incorrect on 31st day

I am experiencing an issue when finding the difference between 2 dates in years. Specifically, when I choose the 31st date, it returns an invalid result as NaN. However, with other dates, the calculation displays the correct outcome. const selectedValu ...

Unable to retrieve elements from the eBay website using JavaScript within a Chrome extension

I recently developed a Chrome extension that scrapes all orders from an eBay orders page. It was working flawlessly last month, but suddenly I am facing issues accessing some elements. Here is the snippet of code causing trouble: let elGridComp = document ...

What is the ideal timing to incorporate an error handler in an Observable?

I find myself uncertain about the best practices for error handling in general. For instance, if I'm already handling errors in my service using catchError, is it necessary to also include an error handler in my subscription? Here's an example o ...

Having trouble with my JSFiddle code not functioning properly in a standard web browser for a Google Authenticator

Here is the code snippet that I am having trouble with: http://jsfiddle.net/sk1hg4h3/1/. It works fine in jsfiddle, but not in a normal browser. I have included the necessary elements in the head to call all the external files. <head> <scri ...

Using JavaScript and jQuery to Sort Telerik RadGrid Client-Side

I'm in need of a solution to organize a rad grid with javascript or jQuery. I am specifically looking for an alternative to using a web service as it is not utilized elsewhere in the project. My approach involves binding to the grid through JavaScrip ...

Is there a way to smoothly navigate back to the top of the page after the fragment identifier causes the page to scroll down?

I do not want to disable the functionality of the fragment identifier. My goal is for the page to automatically scroll back to the top after navigating to a specific section. This inquiry pertains to utilizing jQuery's UI tabs. It is crucial to have ...

Troubleshooting Cross-Origin Resource Sharing (CORS) problem in Jquery

When using AJAX post from jQuery to call two REST services on different domains for business logic, a CORS issue arises. By setting crossDomain: true in my AJAX call following Google references, it works fine without specifying headers. However, if I inc ...

Utilizing JavaScript in Selenium WebDriver, what's the procedure for extracting element information from a script tag?

I'm facing an issue with this particular page There is a canvas element on this page that displays changing numbers whenever the page is refreshed or reloaded. Looking at the source code, I can only find the following: <div class="row"> ...

What is the best way to extract the value of the initial data object from a JSON response that contains multiple data objects with identical names?

Currently, I am trying to integrate a value from a JSON request into a source URL. The code snippet I have below demonstrates my attempt: function Source() { $.ajax({ type: "GET", dataType: "json", url: "https://api.hitbox.tv/media/video/chair ...