根据标记移动 google 地图

Moving the google map according to the marker

我想根据标记移动google地图。我设置了 defaultCenter 但是当我得到我的当前位置时,lat 和 lng 标记正确移动但是 google 地图没有根据标记移动。

这是代码

import { GoogleMap, withScriptjs, withGoogleMap, Marker } from "react-google-maps";
import { useSelector } from 'react-redux';

function Map(props) {
    const { latitude, longitude } = useSelector(state => state.location);
    const [current, setCurrent] = React.useState({ lat: 42.360081, lng: 7.665440 });


    return (
        <GoogleMap defaultZoom={4}
            defaultCenter={{ lat: (latitude ? latitude : current.lat), lng: (longitude ? longitude : current.lng) }}
        >
            {props.isMarkerShown && <Marker position={{ lat: (latitude ? latitude : current.lat), lng: (longitude ? longitude : current.lng) }} />}
        </GoogleMap>
    )
}


const WrappedMap = withScriptjs(withGoogleMap(Map));

const App = () => {
    return (
        <WrappedMap
            isMarkerShown={true}
            googleMapURL={`https://maps.google.com/maps/api/js?key=[API_KEY]-e2c2H2jAcFw`}
            loadingElement={<div style={{ height: `100%` }} />}
            containerElement={<div style={{ height: `75vh` }} />}
            mapElement={<div style={{ height: `100%` }} />}
        />
    )
}

export default App;

尝试将 new window.google.maps.Map 分配给变量 map,然后在 createGoogleMap 函数中添加 setMarker(createMarker(map))

现在标记已放置在地图上,并且地图以其位置为中心,因为您添加了相同的坐标。

查看下面的代码:

googleMapScript.addEventListener("load", () => {
    setGoogleMap(createGoogleMap());
});

...

let createGoogleMap = () => {
    const map = new window.google.maps.Map(googleMapRef.current, {
        zoom: 16,
        center: {
            lat: 43.642567,
            lng: -79.387054,
        },
        // disableDefaultUI: true,
    });

    setMarker(createMarker(map));
}


let createMarker = (map) => {
    const marker = new window.google.maps.Marker({
        position: { lat: 43.642567, lng: -79.387054 },
        map: map,
    })
    return marker
}

截图:

希望对您有所帮助!