简体   繁体   中英

Moving the google map according to the marker

I want to move the google map according to the marker. I set the defaultCenter but when i got my current position with lat and lng marker is move correctly but google map is not moving according to the marker.

Here is the code

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;

Try assigning new window.google.maps.Map to a variable map and then add setMarker(createMarker(map)) in your createGoogleMap function.

Now the marker is placed on the map, and the map is centered on its position because you added the same coordinates.

See the code below:

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
}

Screenshot:

在此处输入图像描述

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM