目标是在地图上显示标记。
我不明白为什么我的标记不显示
我使用react-传单
响应正常,但没有显示
反应
我的地图
进口import { MapContainer, TileLayer, Marker, ScaleControl } from 'react-leaflet';
import tileLayer from '../util/tileLayer';
import L from "leaflet";
import 'leaflet-fullscreen/dist/Leaflet.fullscreen.js';
import 'leaflet-fullscreen/dist/leaflet.fullscreen.css';
import { useEffect } from 'react';
import newMarker from "../data/asset/pin.png";
import axios from 'axios'
第一视图中心
const center = [46.227638, 2.213749];
图标
const pointerIcon = new L.Icon({
iconUrl: newMarker,
iconSize: [50, 58], // size of the icon
iconAnchor: [20, 58], // changed marker icon position
});
标记const MyMarkers = ({ data }) => {
return data.map(({ lat, lng }, index) => (
<Marker
key={index}
position={{ lat, lng }}
icon={pointerIcon}
>
</Marker>
));
}
get data with useEffect, async await &axios
const MapWrapper = () => {
useEffect( async () => {
markers = (await componentDataMarkers()).data
console.log(markers);
}, [])
const componentDataMarkers = async () => await axios.get(`http://localhost:5000/plane/latlong`)
var markers = []
React传单组件
return (
<MapContainer
fullscreenControl={true}
center={center}
zoom={13}
scrollWheelZoom={true}
>
<TileLayer {...tileLayer} />
<MyMarkers data={markers} />
<ScaleControl imperial={false} />
</MapContainer>
)
}
export default MapWrapper;
Marker
位置为类型[lat, lng]
&不是{lat, lng}
。例子——
<Marker position={[51.505, -0.09]} />
:您的data
对象是arrays
的array
。map
功能似乎是不正确的。它需要像markers.map((marker, index) =>
您可以在live editor中尝试的工作示例-
const center = [51.505, -0.09]
const markers = [[51.505, -0.10], [51.505, -0.09], [51.505, -0.08]];
const MyMarkers = ({ data }) => {
return data.map((marker, index) => {
return (
<Marker key={index} position={marker}>
<Popup>
Marker <br /> Popup.
</Popup>
</Marker>
);
});
}
render(
<MapContainer center={center} zoom={13} scrollWheelZoom={false}>
<TileLayer
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<MyMarkers data={markers} />
</MapContainer>,
)
return data.map(({ lat, lng }, index) => (
<Marker
key={index}
position={[ lat, lng ]} // array here
icon={pointerIcon}
>
</Marker>
));
在这里,为什么要从键为0和1的数组中提取lat和lng ?不能使用extract {lat, lng} from array
你可以console.log lat和lng,看看这里是否有数据或未定义吗?