简体   繁体   English

根据标记移动谷歌地图

[英]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.我设置了 defaultCenter 但是当我得到我的当前位置时,lat 和 lng 标记正确移动但谷歌地图没有根据标记移动。

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.尝试将new window.google.maps.Map分配给变量map ,然后在您的createGoogleMap函数中添加setMarker(createMarker(map))

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!希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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