如何使用 google-map-react 显示各种标记

问题描述

我试图通过使用 google-map-react 在我的 React 页面中单击一个按钮来显示各种标记。第一个标记显示正常,但我无法让它显示标记二和三。预期的结果是在任何时候只显示一个标记。我认为我没有正确的组件状态,所以希望得到任何帮助。代码如下:

import React,{ useEffect } from 'react';
import GoogleMapReact from "google-map-react";
import Button from "@material-ui/core/Button";

const place1 = { name: 'Fenway Park',lat: 42.3466764,lng: -71.0972178 };
const place2 = { name: 'northeastern University',lat: 42.3398106,lng: -71.0913604 };
const place3 = { name: 'Wings Over Boston',lat: 42.3404074,lng: -71.0900676 };

function SiteMapPage(props) {
    const [counter,setCounter] = React.useState(1);
    const [place,setPlace] = React.useState(null);

    useEffect(() => {
        setPlaceObject(counter);
        console.log('useEffect called,counter=',counter,',place=',place);
    },[counter]);

    const setPlaceObject = (theCounter) => {
        if (theCounter === 1)      setPlace(place1);
        else if (theCounter === 2) setPlace(place2);
        else if (theCounter === 3) setPlace(place3);
    };

    const handleButtonClick = (event) => {
        const newCounter = counter + 1;
        setCounter(newCounter);
    };

    const handleApiLoadData = (map,maps,thePlace) => {
        console.log('handleApiLoadData called,thePlace=',thePlace);

        if (thePlace) {
            let marker = new maps.Marker({
                animation: maps.Animation.DROP,position: {lat: thePlace.lat,lng: thePlace.lng},map
            });

            marker.customInfowindow = new maps.InfoWindow({
                content: '<div>' + thePlace.name + '</div>'
            });

            marker.addListener('click',() => {
                marker.customInfowindow.open(map,marker);
            });
        }
    };

    return (
        <>
            <div><Button variant="contained" color="primary" onClick={handleButtonClick}>Next Place</Button></div>
            <br/>
            { counter > 0 && place && (
                <>
                    <div>{place.name} - [counter = {counter}]</div><br/>

                    <GoogleMapReact
                        bootstrapURLKeys={{
                            key: process.env.REACT_APP_MAP_KEY,}}
                        defaultZoom={15}
                        defaultCenter={[42.342496,-71.0909205]}
                        yesIWantToUseGoogleMapApiInternals
                        onGoogleApiLoaded={({ map,maps }) => handleApiLoadData(map,place)}
                    />
                </>
            )}
        </>
    );
}

export default SiteMapPage;

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)