One text label to display for a MultiLineString using MapLibre GL JS

I am attempting to show text labels for MultiLineString features within a geoJSON file using MapLibre GL JS. By utilizing the symbol-placement: point option, I aim to display the labels across various zoom levels rather than only when extremely close, as would be the case with the line option.

...

map.addSource('source_data', {
        type: 'geojson',
    data: 'sample.geojson'
});

map.addLayer({
    "id": "symbols",
    "type": "symbol",
    "source": "source_data",
    "layout": {
        "symbol-placement": "point",
        "text-field": '{Name}',
        "text-size": 40,
        "text-justify": "center",
        "text-allow-overlap": false
      }
});

...

My challenge lies in the fact that when there are multiple lines in the MultiLinestring, MapLibre renders a label for each line, as shown in the image below. Is there a method to display only one text label for each MultiLineString feature?

I have provided a sample of the geoJSON file I am working with (containing the two features from the image) since the original file is extensive:

https://i.stack.imgur.com/YW2Md.jpg

Answer №1

To implement a new point source for labeling, I would utilize turf/center of mass to calculate the center point for each feature. This will enable the creation of a layer specifically for labels.

Setup Instructions

npm install @turf/center-of-mass

import centerOfMass from "@turf/center-of-mass";

const yourGeojson = {}
const labelPoints = yourGeojson.features.map(feature => centerOfMass(feature, {properties: {Name: feature.properties.Name}}))

map.addSource('labelSource', {'type': 'geojson', 'data': {type: "FeatureCollection", features: labelPoints}})

map.addLayer({
    'id': 'labelLayer',
    'type': 'symbol',
    'source': 'labelSource',
    'layout': {
        'text-field': ['get', 'Name'],
    }
});

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

NodeJs google analytics reporting API returning null response object

Just getting started with a question. In my project, I am utilizing NodeJS to interact with the Google Analytics Reporting API. I have successfully obtained the necessary OAuth 2 token and even receive a 200 response when querying the API. However, instea ...

Having a minor problem in attempting to retrieve a random value

Having trouble generating a random number from a function. Can someone help explain? const MyButton = document.querySelector(".Flipper"); MyButton.addEventListener("click", recordLog); function recordLog (){ MyButton.style.backgr ...

Manipulating arrays in a JSON file with JavaScript

Struggling with adding a new value to an array stored in a file.json? The array currently contains ["number1", "number2"], and you want to add "number3". However, attempts to define a variable in the JavaScript file containi ...

Retrieving all buttons from a webpage and removing those with a specific background-image using JavaScript

Hey everyone, I'm still learning about javascript and other web development languages. My current task is to locate all the buttons on a webpage and remove the ones that have a specific background image. I know about using getElementsByTagName but n ...

Creating a new buffer by extracting a segment of another buffer in Node.js

Currently, I am executing an AWS call in Node.js that returns a buffer. var aws = new AWS.S3(); var params = { Bucket: s3config.bucket, Key: s3config.tile_directory + filepath //, // Range: 'bytes=0-' + (this.HEADER_SIZE - 1) }; ...

Collaborating and monitoring data between controllers

A unique challenge has arisen as we implement a tree-style navigation element that must communicate with other directives/controllers. The main objectives are: Keep track of the current selection, Detect when the row selection changes. The task at hand ...

Whenever I try to retrieve a value using the key from ModelBindingContext.ValueProvider.GetValue(key

When working with AngularJS to manipulate a complex parent object with different behaviors for its children server-side, I encountered an issue while implementing the CreateModel function as suggested in this answer. The problem arises when any call to bin ...

"Encountered a Http502 error while running the Node component (code provided for reference purposes

Encountering the Http502 error while developing a node component for chatbot. The first code snippet works flawlessly, but the second one triggers an Http502 error. Both snippets share the same host and proxy settings, with only the endpoint being differen ...

Tips for utilizing a for loop within an array extracted from a jQuery element for automation

I am looking to streamline the process using a for loop for an array containing 10 image files in the parameters of initialPreview and initialPreviewConfig. My envisioned solution involves the following code snippet: for (i = 0; i < 11; i++) { "< ...

Issue with triggering jQuery .submit() function on Bootstrap 3 modal form

I've been attempting to use a Bootstrap 3 modal form to trigger a form.submit() in jQuery, but despite my efforts, I can't seem to get it to work as intended. <div class="modal fade" id="modal-signup" tabindex="-1" role="dialog" aria-labelled ...

Encountering difficulties with installing npm dependencies on Windows 7 when using the "npm install" command

I am having trouble installing npm dependencies as outlined in the package.json file by running the npm install command. Despite attempting to use admin rights, I am still encountering the same error. You can view a screenshot of the error here. Below is ...

Create an Android application using Node.js

While developing my mobile application, I am utilizing html5 with node.js to create a chat box for users connected on the same wireless network. However, I encounter an issue when coding on my desktop using node.js software. How can I overcome this challen ...

What are the reasons behind Jquery's decreased speed performance in Internet Explorer?

My ASP.NET page is quite intricate and heavily depends on jQuery for manipulating the DOM without using AJAX. Interestingly, I've observed that the page performs better in Mozilla browsers like Firefox compared to Internet Explorer 7 or 8. Could it b ...

How can I display an ngx spinner after a delay of 1 second?

I am uncertain about the answer I came across on this platform. intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const time = 900; const spinnerLogic = () => { if (this.isRequestServed ...

Using PHP to ascertain the requested dataType or responseType from the client

My ajax request is fairly simple: $.post('server.php',data, function (json) {console.log(json)},'json'); I have configured jQuery to expect json data based on the dataType setting. Question: Is the dataType parameter equivalent to re ...

A guide to incorporating external CSS files in Angular 5 components using styleUrls

I have a unique setup where my Angular 5 application resides in a subdirectory within another parent application. The parent application consists of JSP and other AngularJS applications among other things. My goal is to include a CSS file from the parent ...

Identifying patterns within a string using JavaScript and TypeScript

Given a user-input pattern, for example [h][a-z][gho], and a string "gkfhxhk", I am attempting to determine if the string contains the specified pattern. The pattern dictates that the first character must be 'h', followed by any letter from a-z, ...

Teach me how to utilize Import / require() in Static Folder

I've been attempting this task for a while, but I'm unsure how to incorporate import or require into the express static folder. When I try to use it, I receive an error stating "require not defined" which makes sense since these are not supported ...

Connecting the input[date] and Moment.js in AngularJS

For the purpose of formulating a question, I have prepared a simplified example: ... <input type="date" ng-model="selectedMoment" /> ... <script> angular.module('dateInputExample', []) .controller('DateController', [& ...

TypeScript struggling to recognize specified types when using a type that encompasses various types

I have a defined type structure that looks like this: export type MediaProps = ImageMediaProps | OembedProps; Following that, the types it references are defined as shown below: type SharedMediaProps = { /** Type of media */ type: "image" | "oembed"; ...