google map上的多个标记使用.map

问题描述

我目前正在尝试遍历数组,并在我的react应用程序的google map上显示多个标记。我首先必须通过地理编码api运行位置以获取经纬度,然后设置状态变量以进行映射以获取显示在地图上的标记。我目前在代码中的某处出现问题,似乎找不到问题。

我知道当我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>
    )
}

解决方法

您需要在api调用的成功方法内移动setLatLong(myDiveLogs)。 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>
  )
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...