Rahul Gupta
Rahul Gupta

Reputation: 98

Not able to change center dynamically in React-Leaflet v.3.x

i am working on this React-Leaflet Map. I want to update value of "center" prop of MapContainer based on input provided by User, but it is not working.
I know, methods like flyTo(), panTo() are used in such situations but i don't know where/how to apply them... Please help.
Here's the link to codesandbox https://codesandbox.io/s/stoic-lamport-kk8mj?file=/src/App.js

Upvotes: 3

Views: 2247

Answers (1)

kboul
kboul

Reputation: 14570

From the official docs:

Except for its children, MapContainer props are immutable: changing them after they have been set a first time will have no effect on the Map instance or its container.

As a result, when you change center variable the center does not change. Create a function that changes the map center upon dropdown selection change

function SetViewOnClick({ coords }) {
  const map = useMap();
  map.setView(coords, map.getZoom());

  return null;
}

Include it on MapComp

function MapComp({ coords }) {
  return (
    <MapContainer
      classsName="map"
      center={coords}
      zoom={4}
      scrollWheelZoom={false}
    >
      ...
      <SetViewOnClick coords={coords} />
    </MapContainer>
  );
}

Demo

Note that the coordinates for USA and Canada are not correct so I changed them. They should be

{
  USA: [39.7837304, -100.4458825]
},
{
  Canada: [61.0666922, -107.9917071]
},

and moreover the countries variable does not have to be a state variable as you do not change it. It should be a constant.

Also there is an error in the console because you are using an array on the select element which expects multi selection when using arrays but obviously you do not want that.

Last but not least you should handle the none selection somehow because an error occurs when selecting none.

Upvotes: 5

Related Questions