How to display text on MapBox at specific coordinates?

Viewed 1275

I am currently using MapBox GL JS in my React project.

I want to know how to display some text at specific coordinates after an interaction is over. I get the coordinates of the location from a function getMinCoords()

My current code is as follows

stop() {
    let nextState = this.state;
    if (nextState !== 'Complete') {
      nextState = 'Stop';
    }
    
    if (this.vertices.length > 2) {
      this.annotation.geometries = [{
        type: 'Polygon',
        coordinates: this.GetPolygonCoordinates(),
        properties: {
          annotationType: 'polygon',
        },
      }];
    } else {
      this.annotation.geometries = [];
    }

    console.log(this.getMinCoords());
    this.map.off('click', this.onClickCallback);
    this.setState(nextState);
    this.flushState();
    
  }

The function which takes care of annotations is as follows:

this.geometries.forEach((geometry) => {
      switch (geometry.type) {
        case 'Point':
        case 'LineString':
        case 'Polygon': {
          const styling = GetStyles(geometry, styles);
          const feature = GetFeatureFromGeometry(geometry, this.properties);
          if (this.properties.annotationType === 'label') {
            styling.textAnchor = 'center';
          }
          feature.properties = { ...feature.properties, ...styleProps };
          features.push(feature);
          break;
        }

Before the state is flushed, I want to display the area at the coordinates returned by getMinCoords. I have another function getArea(), which returns the area. I just need to display it on the map

1 Answers

You can create an empty Layer once your map is instantiated with empty source like below:

Code Snippet:

        //Empty Source
        const textGeoJsonSource = {
            type: 'geojson',
            data: featureCollection //Initially this is empty
        };

        //Text Layer with textGeoJsonSource
        const sectionTextLayer: mapboxgl.Layer = {
            "id": "sectionTextLayer",
            "type": "symbol",
            "source": textGeoJsonSource,
            "paint": {
                "text-color": textColor, //Color of your choice
                "text-halo-blur": textHaloBlur,
                "text-halo-color": textHaloColor,
                "text-halo-width": textHaloWidth,
                "text-opacity": textOpacity
            },
            "layout": {
                "text-field": ['get', 't'], //This will get "t" property from your geojson
                "text-font": textFontFamily,
                "text-rotation-alignment": "auto",
                "text-allow-overlap": true,
                "text-anchor": "top"
            }
        };
        this.mapInstance.addLayer(sectionTextLayer);

Then later on set the source of "textGeoJsonSource" to below once you have the coordinates( like getMinCoords in your case ):

{
    "type": "FeatureCollection",
    "features": [
        {
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [ //Pass your coordinates here
                    5.823,
                    -6.67
                ]
            },
            "properties": {
                "t": "18C" //Text you want to display on Map
            }
        }
     ]
}

Please note few things:

  • Your feature collection will need point coordinates in order to show text on Map on that point. If you have a polygon, first get centroid of that polygon for that you can use turf: http://turfjs.org/docs/#centroid

Helpful Links: Centering text label in mapbox-gl-js?

Related