javascript - Google Maps Api:map() 函数不返回标记
问题描述
我使用地震 api通过“react-google-maps”(Doc )获取这个JsonData。但不知何故,标记没有出现,我不明白为什么。
const url =
"https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_day.geojson";
const Map = () => {
const defaultCoordinate = { lat: -0.8962, lng: -91.4445 };
const getMarkers = () => {
FetchEarthquakeData(url).then(result => {
console.log(result.features); //LOG1
result.features.map(earthquake => (
console.log(earthquake), //LOG2
<Marker
key={earthquake.id}
position={{
lat: earthquake.geometry.coordinates[1],
lng: earthquake.geometry.coordinates[0]
}}
/>
));
});
};
return (
<GoogleMap defaultCenter={defaultCoordinate} defaultZoom={8}>
{getMarkers()}
</GoogleMap>
);
};
const WrappedMap = withScriptjs(withGoogleMap(Map));
第一个 console.log (LOG1) 从 JsonData 返回数组。LOG 2 返回数组的每个对象。控制台中没有错误。
解决方案
您需要向(和回调)添加一条return
语句。(但这不是这里唯一的问题,更多信息请参见下面的代码块)getMarkers
.then
问题不是.map
没有返回任何东西,而是getMarkers
没有返回.map
.
更新getMarkers
:
const getMarkers = () => {
return FetchEarthquakeData(url).then(result => {
console.log(result.features); //LOG1
return result.features.map(earthquake => (
console.log(earthquake), //LOG2
<Marker
key={earthquake.id}
position={{
lat: earthquake.geometry.coordinates[1],
lng: earthquake.geometry.coordinates[0]
}}
/>
));
});
};
然而 getMarkers
,它是一个异步函数,因此您不能直接在渲染函数(或功能组件的主体)中使用它的输出。相反,您应该将数据存储FetchEarthquakeData
在状态变量中,然后在渲染时从状态中获取。您还可以在获取地震数据时添加加载状态。
例如:
const url =
"https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_day.geojson";
const Map = () => {
const defaultCoordinate = { lat: -0.8962, lng: -91.4445 };
const [isLoading, setIsLoading] = React.useState(true);
const [earthquakes, setEarthquakes] = React.useState([]);
React.useEffect(() => {
(async () => {
setIsLoading(true);
const result = await FetchEarthquakeData(url);
console.log(result.features); // LOG1
setEarthquakes(result.features);
setIsLoading(false);
})();
}, []);
if (isLoading) {
return "loading...";
}
const markers = earthquakes.map(earthquake => (
console.log(earthquake), // LOG2
<Marker
key={earthquake.id}
position={{
lat: earthquake.geometry.coordinates[1],
lng: earthquake.geometry.coordinates[0]
}}
/>
));
return (
<GoogleMap defaultCenter={defaultCoordinate} defaultZoom={8}>
{ markers }
</GoogleMap>
);
};
const WrappedMap = withScriptjs(withGoogleMap(Map));
注意这里我们把取数据逻辑和渲染逻辑分开,把取到的数据存放在组件的 state 中,然后在渲染的时候就从 state 中取数据。
此外,useEffect
语法可能看起来有点奇怪,但这只是必要的,因为传递给的回调useEffect
不能是异步的,所以我们创建了一个匿名异步函数并立即调用它。
推荐阅读
- cognos - 用户在提示页面上选择提示后,Cognos Analytics 将不会运行
- r - R:data.table:使用随时间引用的聚合
- python - Python 使用请求更改 Instagram 个人资料图片
- performance - 网站大小波动是否正常?
- moodle - 类别中没有足够的问题来创建随机问题
- amazon-web-services - CodeDeploy 代理未在修订相对路径“appspec.yml”的解压缩修订目录中找到 AppSpec 文件
- android - 从 Google Analytics 到 Firebase Analytics 的行为流
- reactjs - React Router 4 的嵌套开关和默认子路由
- python - 从另一个熊猫数据框创建数据框并在同一数据框上应用 Groupby 时无法选择多个列
- python - 将结果作为模型的初始值,但要解决恢复