How to load vector tiles from a binary file using OpenLayers

I'm attempting to load a vector tile in binary format into OpenLayers but I'm facing challenges with the tileLoadFunction. I'm struggling to manually set the data to the tile. The reason why I need to use the tileLoadFunction is because I have to pass an API key to authenticate with the tile server. This is the current code snippet I have:

    let http = HttpClient;

    let layer = new VectorTileLayer();
    layer.setSource(
      new VectorTileSource({
        format: new MVT(),
        url: 'TILE_SERVER_URL',
        tileLoadFunction: (tile, src) => {
          // set headers
          const headers = new HttpHeaders({
            accept: 'application/binary',
            'authentication_id': environment.auth_token,
          });
         
          // retrieve the tiles
          this.http
            .get(src, {
              headers: headers,
              responseType: 'blob',
            })
            .subscribe((data) => {
              if (data !== undefined) {
                console.log(data);
                let vector_tile = tile as VectorTile;
                const format = new MVT();
                // Setting the features as follows is not valid
                // vector_tile.setFeatures(format.readFeatures(data, {}));
              } else {
                tile.setState(TileState.ERROR);
              }
            });
        },
      })
    );

I've looked for similar examples but haven't found any that guide me in the right direction.

Answer №1

One of the key errors made was using the arraybuffer type instead of the blob type, resulting in the following consequences:


import MVT from 'ol/format/MVT';
import VectorTileLayer from 'ol/layer/VectorTile';
import VectorTileSource from 'ol/source/VectorTile';

    layer.setSource(
      new VectorTileSource({
        url: 'https://your-vector-tile-api/{z}/{x}/{y}.pbf',
        format: new MVT(),
        tileLoadFunction: (tile: any, src) => {
          tile.setLoader(
            (extent: Extent, resolution: number, projection: Projection) => {
              // set headers
              const headers = new HttpHeaders({
                accept: 'application/binary'
              });

              this.http
                .get(src, {
                  headers: headers,
                  responseType: 'arraybuffer',
                })
                .subscribe((data: any) => {
                  if (data !== undefined) {
                    const format = new MVT();

                    let features = format.readFeatures(data, {
                      extent: extent,
                      featureProjection: projection,
                    });
                    tile.setFeatures(features);
                    this.map.updateSize();
                  } else {
                    this.logger.error('error while loading features');
                    tile.setState(TileState.ERROR);
                  }
                });
            }
          );
        },
      })
    );

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

Using Typescript to remove an element from an array inside another array

I've encountered an issue while trying to remove a specific item from a nested array of items within another array. Below is the code snippet: removeFromOldFeatureGroup() { for( let i= this.featureGroups.length-1; i>=0; i--) { if( this.featureGr ...

Why does the event fail to trigger in an Angular 5 Kendo grid when the last character is deleted from the input box?

I have implemented a multi-filter in my Kendo Grid for an Angular 5 application. However, I am facing an issue where the event is not firing when the last character is deleted from the input box. How can I resolve this issue? For example, if I type ' ...

Expanding interfaces dynamically in Typescript

Currently, I am facing a challenge while attempting to integrate an existing React Native module equipped with the following props: useComponent1: boolean useComponent2: boolean This is how the implementation looks like: render(){ if(useComponent1){ ...

What is the process of converting a byte array into a blob using JavaScript specifically for Angular?

When I receive an excel file from the backend as a byte array, my goal is to convert it into a blob and then save it as a file. Below is the code snippet that demonstrates how I achieve this: this.getFile().subscribe((response) => { const byteArra ...

Align item in center of remaining space within container using Material-UI React

I am relatively new to MUI and styling HTML components, and I have a query. I'm currently utilizing the Grid feature in my React project. My goal is to achieve something similar to this (image edited in Paint, alignment may not be accurate): https://i ...

Attempting a second filter of the table using the dropdown results in no data being returned

I've developed a CRUD app using Angular 7, and I'm facing an issue. When I select a dropdown item for the first time, it shows the desired table data. However, on selecting another item for the second time, it returns nothing. Below is my compone ...

Error Type: TypeError when using Mongoose's FindOneAndUpdate function

I am encountering difficulties while trying to implement a findOneAndUpdate query. //UserController UserDAO ['findOneAndUpdate'](userId, {& ...

Using command line arguments in a Tauri project with a Next.js frontend

I am utilizing Tauri.JS in conjunction with Next.js. In this scenario, I need to execute the console command: npm run tauri dev --<argument name>=<some value>. Afterwards, I should be able to access the value of the argument in my JavaScript ...

Unable to convert JSON data for integration with rxjs

I am currently using a webSocket to receive data from my server. I have created an rx Subject called MessageEvent that allows me to retrieve the data. However, although I can successfully log the JSON data in my observable, I am unable to access any prope ...

Issues with mat-input functionality within a mat-table in Angular 8

I'm encountering an issue with my mat-table. The input field within the table is not functioning properly. All rows are sharing the same input field, so when I type text into the box, it appears in all rows. Here is my code: <ng-container matColum ...

What is the best method for launching a Node.js (Express) app on a live server automatically?

My Angular app relies on an express backend. What is the best way to deploy this application on a remote server so that it always runs smoothly? ...

Binding the same object to itself in Angular using @Input, with different property names

In the documentation, I came across a method to modify property names like this: @Input('account-id') id: string; Is it possible to alter property names within an object to different titles? I've developed a flexible radio button component ...

Do not directly change a prop's value as it will be replaced when the parent component re-renders. Use v-form instead

I'm currently in the process of developing an app using nuxt along with vuetify 2.x, and I keep encountering a specific error message: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Inste ...

Is the Content-Type header leading to an Unsupported Media Type error?

I encountered an unexpected error while attempting to post an element using my backend API. The API is returning a 415 error code, specifically related to the Media Type: Failed to load resource: the server responded with a status of 415 () The error me ...

What is the best way to utilize a React type as props for a custom component?

To make my component work properly, I am required to pass the inputmode as props from an external source. The acceptable values for <input inputMode=<valid values>> are outlined in the React types (node_modules@types\react\index.d.ts) ...

Angular Update Component on Input ChangeEnsuring that the component is automatically

<div class=" card-body"> <div class="row"> <div class=" font-icon-list col-lg-2 col-md-3 col-sm-4 col-xs-6 col-xs-6" routerLinkActive="active" *ngFor="let subject of subjects"> <div class=" fon ...

Accessing arrays using bracket notation

When working with TypeScript (or JavaScript), you have the option to access object properties using either dot notation or bracket notation: object.property object['property'] Let's explore a scenario using the latter method: const user = ...

Validation with React Hooks does not function properly when used on a controlled component

I've recently started using react hook form and I've created a custom component based on material ui's autocomplete. The issue I'm facing is that react hook form isn't validating the field at all. Let me show you how the setup look ...

Troubleshooting Angular 2 Fallback Route Failure

My current project is using Angular 2 Webpack Starter but I am having trouble with the fallback route. In my app.routes.ts file, I have defined the routes as follows: import { Routes } from '@angular/router'; import { HomeComponent } from &apos ...

What type of HTML tag does the MUI Autocomplete represent?

Having trouble calling a function to handle the onchange event on an autocomplete MUI element. I've tried using `e: React.ChangeEvent`, but I can't seem to locate the element for the autocomplete component as it throws this error: The type &apos ...