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>
    );
  }
}

3
  • 1
    Check out this answer on using a leaflet tooltip as a map label, and this answer 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 Commented Mar 10, 2021 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 Commented Mar 10, 2021 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. 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 Commented Mar 10, 2021 at 20:16

0

Browse other questions tagged or ask your own question.