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

Obtaining the MapOptions object from a map using Google Maps API version 3

Previously in Google Maps api v2, you were able to retrieve map parameters like the type and zoom directly from the map object. However, in version 3, the setOptions method is used to configure parameters, but there is no equivalent method like getOption ...

Obtain an oAuth token through the use of npm

Recently, I've been working on a nodeJS service to fetch an OAuth token from a server. Unfortunately, I keep encountering errors when running the function below: var express = require('express') var http = require('http'); var htt ...

Ag-Grid: Matching colors with filtering functionality

Can AG-Grid be configured to highlight matching cells during quick filtering? For example, if I have the following data: [ { firstName: 'Tom', lastName: 'Doe', company: 'Tesla' }, { firstName: 'Tim', lastName: & ...

Angular UI directive for modal confirmation

Looking to create a custom Angular directive using angular-bootstrap that mimics the confirm() function. Check out the visual result and desired behavior in this plunk: http://embed.plnkr.co/27fBNbHmxx144ptrCuXV/preview Now, I want to implement a directi ...

Utilize moment.js to convert an epoch date into a designated time zone

I've spent countless hours searching for a resolution to the issue with moment.js and its inability to accurately display the correct date for a given local time zone. Let me explain my predicament: The flight API I'm utilizing provides me w ...

Transfer a file from the file:///var/mobile/Applications/ directory to an accessible location for reading in Cordova/PhoneGap

I have a unique 'whitelabel' app that customizes itself for each client by downloading image files from a configuration server. However, I am facing an issue where the images are not displayed and instead showing a "Not allowed to load local reso ...

Tips on adding a base64 encoded image string to a JSON object using JavaScript

I'm trying to convert an image file into a JSON object using JavaScript. I've managed to turn the image into a string by utilizing base64 encoding, but I'm unsure how to then convert this string into a JSON object. Can anyone help? ...

Create a form in a PHP file containing a pair of buttons for selecting a specific action

Consider the following HTML code snippet: <body onload="showcontent()"> <!-- onload attribute is optional --> <div id="content"><img src="loading.gif"></div> <!-- exclude img tag if not using onload --> < ...

Displaying Material UI Styles: A Challenge

Currently working on a website using Material-UI and React. Strangely, the styling applied through Material-UI's Hook API functions perfectly on codesandbox.io but fails to work when running locally. Notably, the border radius feature fails to update ...

Does JSON hijacking play a role with IE versions greater than 10 or Chrome versions greater than 30?

OWASP suggests wrapping json response with an object rather than returning a direct array. For instance: [{"id":5}] Is this vulnerability still relevant? Could it be exploited? After testing in Chrome, IE, and FF, I couldn't find a way to 'h ...

Guide to iterating through three dynamic arrays containing objects in C# for parsing a JSON string

Hey there! I'm currently working on a parser that can handle a JSON string made up of 3 different dynamic arrays of objects. Take a look at the example below. The challenge is, I have no idea about the length of each object in the arrays. My ultimate ...

Utilizing a Custom Validator to Compare Two Values in a Dynamic FormArray in Angular 7

Within the "additionalForm" group, there is a formArray named "validations" that dynamically binds values to the validtionsField array. The validtionsField array contains three objects with two values that need to be compared: Min-length and Max-Length. F ...

The retrieved item has not been linked to the React state

After successfully fetching data on an object, I am attempting to assign it to the state variable movie. However, when I log it to the console, it shows as undefined. import React, {useState, useEffect} from "react"; import Topbar from '../H ...

Arranging an array of objects in typescript with elements implicitly having an undefined type

Currently, I am facing a challenge where I need to sort an array of objects within a function. The catch is that the function receives the key as a parameter, making it unknown: export interface ProductsList { id: boolean nome: string qtde: number ...

Combining jQuery form validation with a PHP script on a single webpage

After implementing jQuery form validation and redirecting using the function btn_onclick() { window.location.href = "http://localhost/loginprivate.php";} from index.php to loginprivate.php, my web app's PHP script is not being executed. The user is re ...

DataGrid Component: Implementing a Button for Deleting Rows

I am currently developing a React component with MaterialUI, incorporating a Datagrid to manage a queue of files. The layout resembles this: One functionality I'm focusing on is when the user clicks on the three dots at the end of each row, a Menu (c ...

What is the process for establishing a dependency on two distinct JavaScript files, similar to the depends-on feature found in TestNG?

I am faced with a scenario where I have two separate JS files containing test methods, namely File1 and File2. The requirement is that File2.js should only be executed if File1.js has successfully completed its execution. My current setup involves using ...

Interacting with Apexcharts: Exploring a Tiny Column with Hover

While using apexcharts, I encountered an issue with small columns. It can be quite challenging to render the tooltip properly because you have to hover very precisely over the column. Query: Is there a way to expand the hover area to make it easier to int ...

Using PHP script, extract information from a JSON file and populate a dropdown menu in HTML

I am attempting to extract data from a JSON file using PHP and then display this data in an HTML select tag on the front end. Below is my PHP file: <?php ini_set('display-errors', 'on'); error_reporting(E_ALL); $executionStartTim ...

Unable to resolve the issue with ExpressPeerServer not being recognized as a function in server.js

I'm facing an issue with the peer.js library in my npm project. I have successfully installed it, but when I try to use it in my server.js file, I get an error saying that peerServer is not a function. const express = require('express'); con ...