简体   繁体   中英

How to add coordinates from db to Marker react leaflet

From the database, I receive coordinates that lie in the form of two fields: "lat" and "lon". On the map I use several makers. How can I combine these two fields to pass coordinates(coord.lat and coord.lon) to the Marker component at position? I tried to add, but you can't pass values to props separated by commas.

 const Map = () => { 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} position={coord.lat, coord.lon} icon={defaultIcon} /> ))} </MapContainer> </div> ); };
在此处输入图像描述

在此处输入图像描述

A React-Leaflet Marker gets its position data in a float array with two values:

[51.234, 23.654]

So you would first need to get the latitude and longitude in an array as floats - it seems in your data format you have the coordinates as float-formatted strings in the lat and lon properties so you could do it like so:

const position = [parseFloat(coord.lat), parseFloat(coord.lon)]

Then you would just pass this array as the property:

<Marker key={index} position={position} icon={defaultIcon} />

So the whole block of populating markers from the coordinates list would be something like:

{coordinates.map((coord, index) => {
    const position = [parseFloat(coord.lat), parseFloat(coord.lon)]
    return <Marker key={index} position={position} icon={defaultIcon} />
)}

Or you could just inline it (to avoid writing a full function body for the map) like:

{coordinates.map((coord, index) => (
          <Marker key={index} position={[parseFloat(coord.lat), parseFloat(coord.lon)]} icon={defaultIcon} />
        ))}

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