【发布时间】:2021-10-04 03:43:30
【问题描述】:
我不明白为什么这不会显示来自 NASA api 的野火数据。纬度和经度是正确的,我可以使用标记组件使单个标记出现在屏幕上,而不是野火事件数组。为什么这些标记不显示?数组中有300多个元素
import GoogleMapReact from 'google-map-react';
import { useSelector } from 'react-redux';
function App() {
const wildfires = useSelector((state: any)=>state.wildfires);
console.log(wildfires);
return (
<div className="App">
<header className="App-header">
Wildfires: {wildfires.length}
<Map
lat={41.000418}
lng={-123.0483683}
zoom={9}
wildfires={wildfires}/>
</header>
</div>
);
}
const Marker = (props: any) => {
const { color, name } = props;
const el = (
<div className="marker"
style={{ backgroundColor: color, cursor: 'pointer'}}
title={name}/>
)
return (el)
};
const renderMarkers = (map: any, maps: any, wildfires: any) => {
for(const item of wildfires){
let marker = new maps.Marker({
position: {lat: item.geometry[0].coordinates[0], lng: item.geometry[0].coordinates[1]},
map,
title: 'My Marker'
});
}
}
const Map = (props: any) => {
const loading = useSelector((state: any) => state.wildfiresLoading)
const points = props.wildfires.map((w: any)=>{
return {
lat: w.geometry[0].coordinates[0],
lng: w.geometry[0].coordinates[1]
}
})
console.log(points);
return (
<div style={{ height: '100vh', width: '100%' }}>
{!loading ? <GoogleMapReact
bootstrapURLKeys={{ key: "AIzaSyAe3TSmPP1WlHUFrOUwnA-okBcB2DfH-BI"}}
defaultCenter={{
lat: props.lat,
lng: props.lng
}}
yesIWantToUseGoogleMapApiInternals={true}
defaultZoom={props.zoom}
// onGoogleApiLoaded={({map, maps}) => renderMarkers(map, maps, props.wildfires)} //Sadly this didn't work
>
{props.wildfires.map((w:any, i:any)=><Marker
key={w.id}
lat={w.geometry[0].coordinates[0]}
lng={w.geometry[0].coordinates[1]}
name={w.title}
color="red"
/>
)}
</GoogleMapReact> : <div>loading</div>}
</div>
);
}
// Api / Redux
import axios from 'axios'
export function getWildfires() {
return function(dispatch: any) {
dispatch(setWildfiresLoading(true));
return axios.get("https://eonet.sci.gsfc.nasa.gov/api/v3/events?category=wildfires&status=open")
.then(( res ) => {
dispatch(setWildfires(res.data.events));
dispatch(setWildfiresLoading(false));
});
};
}
export function setWildfires(wildfires: any) {
return {
type: "SET_WILDFIRES",
payload: wildfires
}
}
export function setWildfiresLoading(loading: Boolean) {
return {
type: "SET_WILDFIRES_LOADING",
payload: loading
}
}
export const wildfireReducer = function (state = {wildfires: []}, action: any) {
switch (action.type) {
case "SET_WILDFIRES":
return {
...state,
wildfires: action.payload
};
case "SET_WILDFIRES_LOADING":
return {
...state,
wildfiresLoading: action.payload
};
default:
return state;
}
};
【问题讨论】:
-
你试过我的解决方案了吗?它对你有用吗?希望对您有所帮助。
标签: reactjs google-maps react-redux react-hooks google-maps-react