简体   繁体   中英

React with Google Maps Api, how to recenter map

I'm using react and using the map as a functional component. (tbh I'm still unsure as to when to use classes v. functions when it comes to classes). however my main issue is that I'm using the google Maps API to present a map and I'm trying to center a map on the users current location. also, I wanted it to update as they walked around so I was just going to use a set interval function to set a timer of when it updates. I thought that the navigator would be my best bet. Although I can't seem to find a proper function to update the center property after initialization.

I'll mark where I think the function should go.

Here's the documentation I've been looking at: https://tomchentw.github.io/react-google-maps/#googlemap

function MapContainer() {
    const [currentLoc,setCurrentLoc] = useState(
        {
            lat: 42.331429,
            lng: -83.045753
        }
    )
    function setLocation() {
        if(navigator.geolocation)
        {
            navigator.geolocation.getCurrentPosition(
                (position) => {
                    setCurrentLoc(position.coords.latitude,position.coords.longitude)
                }
            )
        }
    }
   
    return (
    <LoadScript
      googleMapsApiKey="Api key"
    >
      <GoogleMap
        //THIS IS WHERE YOU STYLLLLLEEEE
        //also where you set what is visible with the controls
        options= {{
            styles:mapStyles['hide'],
            mapTypeControl:false,
            disableDefaultUI:true,
            draggable:true,
            zoomControl:true
        }}
        id="44b929060bf5f087"
        mapContainerStyle=
        {{
            height: "86.5vh",
            width: "100%",
            stylers: mapStyles['hide'],
            draggable: false
        }}
        center={{
            lat: 44.331429,
            lng: -83.045753
        }}
        zoom={10}
      >
        {
            setInterval((props) => {
                var long;
                var lati;
                if(navigator.geolocation)
                {
                    navigator.geolocation.getCurrentPosition(
                        (position) => {
                            lati = position.coords.latitude;
                            long = position.coords.longitude;
                        }
                    )
                };
                //here is where i'd set the center if i had a function i could do it with
            }, 2000)
        }
      </GoogleMap>
    </LoadScript>
  )
}
 
export default MapContainer;

I can't access the documentation link of react-google-maps library . You can use the @react-google-maps/api library since this is a rewrite of the react-google-maps and is more maintained.

For your use case, you can set the value of your center in a state and update it in the setinterval function. This way, each time the state value of the center changes, the center also changes. Please see this sample code and code snippet below:

import React from "react";
import { GoogleMap, LoadScript } from "@react-google-maps/api";

const containerStyle = {
  width: "400px",
  height: "400px",
};

function MyComponent() {
  const [map, setMap] = React.useState(null);
  const [currentLoc, setCurrentLoc] = React.useState({
    lat: 42.331429,
    lng: -83.045753,
  });

  const onLoad = React.useCallback(function callback(map) {
    setMap(map);

    setInterval((props) => {
      console.log("refreshed");
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition((position) => {
          setCurrentLoc({
            lat: position.coords.latitude,
            lng: position.coords.longitude,
          });
        });
      }
    }, 2000);
  }, []);

  return (
    <LoadScript googleMapsApiKey="YOUR_API_KEY">
      <GoogleMap
        mapContainerStyle={containerStyle}
        center={{ lat: currentLoc.lat, lng: currentLoc.lng }}
        zoom={10}
        onLoad={onLoad}
      >
        {/* Child components, such as markers, info windows, etc. */}
        <></>
      </GoogleMap>
    </LoadScript>
  );
}

export default React.memo(MyComponent);

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