Home > Enterprise >  Adding countries name on the map in react maps
Adding countries name on the map in react maps

Time:01-04

I want to use this map and here is it's link : https://www.react-simple-maps.io/examples/map-chart-with-tooltip/

The problem is that the user have to hover on the geographies to see the country name , but I want the name to be on the geographies too .

CodePudding user response:

You can achieve this using the inbuilt functionality of this npm called marker.

marker's documentation

I tried implementing on my own but this feature require the set of coordinates to pass into the marker which will set your marker on their respective country in your case

i am still posting the code i have tried , you just have to pass an array of the coordinates to this marker

import React, { memo } from "react";
import {
 ZoomableGroup,
 ComposableMap,
 Geographies,
 Geography,
 Marker,  // import this 
 text.    // import this
} from "react-simple-maps";

const geoUrl =
"https://raw.githubusercontent.com/zcreativelabs/react-simple- 
 maps/master/topojson-maps/world-110m.json";

const rounded = num => {
 if (num > 1000000000) {
  return Math.round(num / 100000000) / 10   "Bn";
 } else if (num > 1000000) {
   return Math.round(num / 100000) / 10   "M";
 } else {
   return Math.round(num / 100) / 10   "K";
 }
};

const MapChart = ({ setTooltipContent }) => {
return (
 <>
  <ComposableMap data-tip="" projectionConfig={{ scale: 200 }}>
    <ZoomableGroup>
      <Geographies geography={geoUrl}>
        {({ geographies }) =>
          geographies.map(geo => {
        const { NAME, POP_EST } = geo.properties;
        setTooltipContent(`${NAME} — ${rounded(POP_EST)}`); // i have set the state outside of the tooltip
        return(
          <>
        <Geography
              key={geo.rsmKey}
              geography={geo}
              style={{
                default: {
                  fill: "#D6D6DA",
                  outline: "none"
                },
                hover: {
                  fill: "#F53",
                  outline: "none"
                },
                pressed: {
                  fill: "#E42",
                  outline: "none"
                }
              }}
            />
             <Marker coordinates={[-101, 53]} fill="#777"> // pass an array of coordinates here 
              <text textAnchor="middle" fill="#F53">
               {NAME, POP_EST}
             </text>
            </Marker>
          </>
          )
      })
        }
      </Geographies>
    </ZoomableGroup>
  </ComposableMap>
</>
);
};

export default memo(MapChart);

i have tried with a single marker on the screen and it works as expected, please do let me know if this was any helpful , cheers !

  •  Tags:  
  • Related