3

I have GeoJSON that has names and polygons for every country in the world. I have successfully rendered polygons (which is basically world map) but I don't know how to show names of countries inside each polygon. It would be also nice if I could show names only if they fit inside a polygon based on zoom level. I know i can get polygon center with const center = layer.getBounds().getCenter(); but I just don't know what to do with it. This is my code so far

import React, { Component } from "react";
import { MapContainer, GeoJSON } from "react-leaflet";
import countriesData from "../data/countries.json";
import "leaflet/dist/leaflet.css";
import "./Map.css";

export default class Map extends Component {
  onEachCountry = (country, layer) => {
    const countryName = country.properties.ADMIN;

    layer.on({
      mouseover: (e) => {
        e.target.setStyle({
          color: "red",
        });

      },
      mouseout: (e) => {
        e.target.setStyle({
          color: "black",
        });
      },
    });
  };

  render() {
    return (
      <div>
        <MapContainer style={{ height: "80vh" }} center={[0, 0]} zoom={1.5}>
          <GeoJSON
            style={{
              color: "black",
              weight: 1,
            }}
            data={countriesData.features}
            onEachFeature={this.onEachCountry}
          ></GeoJSON>
        </MapContainer>
      </div>
    );
  }
}

  • 1
    Check out [this answer](https://stackoverflow.com/a/59242405/12010984) on using a leaflet tooltip as a map label, and [this answer](https://github.com/PaulLeCam/react-leaflet/issues/291#issuecomment-284576623) on how to use it in RL. As far as only showing the label only if it fits within the shape at a given map scale, that is a *very* interesting question, and coding that from scratch sounds like quite the job. Are you sure you don't want to use an existing reference layer, like esri's [world light grey reference](https://www.arcgis.com/home/item.html?id=87fcdf91a0f14e4a9fda40a763c6f2b8) – Seth Lutske Mar 10 '21 at 17:12
  • I have already seen these answers you linked but they don't solve my problem. I just though, since these "_responsive_" labels are common map feature, there would be a leaflet method to add them. I will try to find some existing reference layers. Thank you! @SethLutske – Nemanja Gakovic Mar 10 '21 at 20:01
  • I don't think there's any existing built-in leaflet functionality, or even any plugins for this. Building them from scratch from a GeoJSON would be tough, as far as I know, though it looks like [it has been done before](https://gis.stackexchange.com/questions/245621/how-to-label-geojson-points-in-leaflet). In your use case, considering you want to show your own customized GeoJSON, I would consider a pre-fab labels layer. You can even build your own and import them into your map use Mapbox Studio. Just some ideas – Seth Lutske Mar 10 '21 at 20:16

0 Answers0