zcreativelabs / react-simple-maps

Beautiful React SVG maps with d3-geo and topojson using a declarative api.
https://www.react-simple-maps.io/
MIT License
3.04k stars 424 forks source link

Example for parseGeographies? #216

Open marty331 opened 4 years ago

marty331 commented 4 years ago

I don't see any example on how to populate the parseGeographies property for Geographies. Could someone add an example?

soncomqiq commented 3 years ago

I'm not sure do I use it in the right way. But it worked for me. In my case, I want to change map depends on URL state.

import {feature} from 'topojson-client';

export function ManageMap() {
  const [mapUrl, setMapUrl] = useState("");
  const [geographyMapData, setGeographyMapData] = useState([]);

  const fetchGeography = async (url) => {
  const res = await fetch(url);
  const data = await res.json();
    return data;
  }

  useEffect(() => {
     fetchGeography(mapUrl).then(res => { setGeographyMapData(res.data) });
  }, [mapUrl])

return (
<>
  <button onClick={() => setMapUrl("anotherURL")}>Change URL Map</button>
  <ComposableMap
      projection="geoMercator"
      projectionConfig={{
      center: [longitude, latitude],
            scale: scale,
      }}
      >
            <ZoomableGroup center={[longitude, latitude]}>
                  // I put the geopraphy value because If I don't put it, the parseGeoprahies will not be excuted.
                  <Geographies geography="http://localhost:8080/api/admins/maps" parseGeographies={(geo) => {
                        if (geographyMapData.objects) {
                              return feature(geographyMapData, geographyMapData.objects[Object.keys(geographyMapData.objects)[0]]).features;
                        }
                        return geo;
                  }}>
                    {({geographies}) =>
                        geographies.map((geo) => (
                            <Geography
                                style={{
               ........
               ........
               ........
}

PS. Actually, I use react-query to fetch data. But I convent it to normal axios for newbies.

adamzwasserman commented 3 years ago

It looks to me like parseGeographies is not a prop, but rather an optional parameter to pass a function to the the function. Just assign a function to parseGeographies (as in the example above) and when the Geographies component calls the getFeatures function from utils.js (https://github.com/zcreativelabs/react-simple-maps/blob/master/src/utils.js) it will call the passed function with the topojson geographies as the input to the function.

Sorry of my explanation is not as clear as I would like. I am not the world's greatest programmer. :(