Is there a way to center text inside a polygon in Leaflet?

Viewed 738

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

0 Answers
Related