简体   繁体   中英

How to change the information when clicking on a marker in React-leaflet?

I have a React-leaflet map on the left side with markers placed on it. On the right side there is a list of point names. I need that when clicking on a certain marker, the name of the point that corresponds to the marker becomes 1st in the list. I take the coordinates of the points and the name of the places from the Firestore. How can I implement this behavior? App.js:

 function App() { const [selectedHouse, setSelectedHouse] = useState(); return ( <div className="App"> <Header /> <div className="map-content"> <Map onSelect={setSelectedHouse} /> <List selectedHouse={selectedHouse} /> </div> </div> ); }

Map.js:

 const Map = ({ onSelect }) => { const [coordinates, setCoordinates] = useState([]); useEffect(() => { const q = query(collection(db, "map-markers")); onSnapshot(q, (querySnapshot) => { setCoordinates( querySnapshot.docs.map((doc) => ({ id: doc.id, data: doc.data(), })) ); }); }, []); return ( <div style={{ width: "100%" }}> <MapContainer center={center} zoom={13} scrollWheelZoom={false} style={{ height: "100vh" }} > <TileLayer attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" /> {coordinates.map((coord, index) => ( <Marker key={index} eventHandlers={{ click: () => { onSelect(index); }, }} position={[parseFloat(coord.data.lat), parseFloat(coord.data.lon)]} icon={defaultIcon} /> ))} </MapContainer> </div> ); };

List.js:

 const List = ({ selectedHouse }) => { const [houseTitles, setHouseTitle] = useState([]); useEffect(() => { const q = query(collection(db, "map-markers")); onSnapshot(q, (querySnapshot) => { setHouseTitle( querySnapshot.docs.map((doc) => ({ id: doc.id, data: doc.data(), })) ); }); }, []); return ( <div style={{ width: "50%" }}> {houseTitles.filter((title, index) => index.== selectedHouse),map((title. index) => ( <ListItem key={index} title={title.data;title} /> ))} </div> ); };

在此处输入图像描述

In your List.js you need to add the selected house before the .map part so that the selected house properly appears:

    <div style={{ width: "50%" }}>
      {<ListItem title={houseTitles[selectedHouse]} />}
      {houseTitles
        .filter((title, index) => index !== selectedHouse)
        .map((title, index) => (
          <ListItem key={index} title={title.data.title} />
        ))}
    </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM