【发布时间】:2020-09-29 18:23:08
【问题描述】:
我不熟悉反应和构建应用程序以更好地理解它。我目前正在使用 Google maps api 来渲染地图,并希望将多个标记渲染到地图上。
我必须使用地理编码 api 来获取我的每个位置的纬度和经度,以便我可以将它们作为标记显示在地图上。目前我的代码没有在屏幕上显示任何内容,我认为这是因为地图在 fetch 调用完成之前尝试使用空状态变量渲染标记。
我试图寻找答案,但找不到与我尝试做的类似的任何事情。
这是我的代码
import React, { useContext, useEffect, useState } from 'react';
import { GoogleMap, useLoadScript, Marker } from "@react-google-maps/api"
import Settings from "../Settings"
import mapSyles from "./MapStyles"
import { LogContext } from '../divelog/DiveLogProvider';
export const MapRender =(props) => {
const {diveLogs} = useContext(LogContext)
const [latLong, setLatLong] = useState()
//get the logs location and run that through api to get lat and long
useEffect(()=>{
let latLongs = []
diveLogs.map(dl =>{
return fetch(`http://api.positionstack.com/v1/forward?access_key=MYKEY&query=${dl.location}&limit=1
`)
.then(res => res.json())
.then(parsedRes => {
latLongs.push(parsedRes.data[0])
})
})
setLatLong(latLongs)
console.log(latLong)
},[diveLogs])
//here I want to map through the state variable and display all of the markers on the map
return (
<div>
<GoogleMap
mapContainerStyle={mapContainerStyle}
options={options}
zoom={1}
center={center}
>
{
//this is where I map through the state variable
latLong.map(l =>(
<Marker key={l.lat}
position ={{lat: l.latitude, lng: l.longitude}}
/>
))
}
</GoogleMap>
</div>
)
}
【问题讨论】:
标签: javascript reactjs google-maps