[英]Multiple markers on google map React with a .map
我目前正在嘗試遍歷數組並在我的 React 應用程序的谷歌地圖上顯示多個標記。 我首先必須通過地理編碼 api 運行位置以獲取 lat 和 lng,然后設置一個狀態變量來映射以獲取要顯示在地圖上的標記。 我目前在我的代碼中的某個地方遇到了問題,似乎無法找到問題所在。
我知道當我 console.log 我的狀態變量時,它似乎多次運行日志,前幾個是空數組,最后幾個包含我需要的數據。 我對反應很陌生,仍然試圖掌握它。
此外,我認為我的 .map 函數在設置狀態變量之前正在運行,我不確定如何重構以解決這個問題。
這是我的代碼 -
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([])
useEffect(()=>{
//Taking the logs and running them through API to get lat and lng for each location
let latLongs = []
diveLogs.map(dl =>{
return fetch(`http://api.positionstack.com/v1/forward?access_key=ff0fcd042ab984146219abc275c71e4b&query=${dl.location}&limit=1
`)
.then(res => res.json())
.then(parsedRes => {
latLongs.push(parsedRes.data[0])
setLatLong(latLongs)
})
})
},[diveLogs])
// this returns several logs, the first of which are empty arrays and the last are correct with the data that I need
console.log(latLong)
const { isLoaded, loadError } = useLoadScript({
googleMapsApiKey: Settings.apiKey
})
const mapContainerStyle = {
width: '31rem',
height: '24rem'
}
const center = {
lat: 0,
lng: 0
}
const options = {
styles: mapSyles,
disableDefaultUI: true
}
if (loadError) console.log("error loading maps")
if (!isLoaded) return "Loading..."
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>
)
}
您需要將 setLatLong(myDiveLogs) 移動到 api 調用的成功方法中。 Api 調用是異步的,但在 setLatLong 中分配數據是同步的。 React 將在 setLatLong 中推送空數據。
您需要等待 api 調用,一旦數據可用,請在其中設置值。
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([]) useEffect(() => { //Taking the logs and running them through API to get lat and lng for each location let myDiveLogs = [] 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 => { myDiveLogs.push(parsedRes.data[0]) setLatLong(myDiveLogs) }) }) }, [diveLogs]) // this returns several logs, the first of which are empty arrays and the last are correct with the data that I need console.log(latLong) const { isLoaded, loadError } = useLoadScript({ googleMapsApiKey: Settings.apiKey }) const mapContainerStyle = { width: '31rem', height: '24rem' } const center = { lat: 0, lng: 0 } const options = { styles: mapSyles, disableDefaultUI: true } if (loadError) console.log("error loading maps") if (!isLoaded) return "Loading..." 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> ) }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.