I'm trying to use a button to pan the google map to the users current location. The panTo is effective but only on number values. I try using the parseFloat method on the values returned by the geolocation, but it doesn't work.
The error I receive is 'not a LatLng or LatLngLiteral with finite coordinates: in property lat: NaN is not an accepted value', name: 'InvalidValueError', stack: 'Error\n'
const AddSpotPage = (props) => {
const {isLoaded}= useJsApiLoader({
googleMapsApiKey: process.env.REACT_APP_GOOGLE_MAPS_API_KEY,
})
const [map, setMap]= useState( /** @type google.maps.GoogleMap */ (null))
**let userLat;
let userLong;
let test = {lat: parseFloat(userLat), lng: parseFloat(userLong)}**
let center = {lat: 50.8584, lng: 12.2945}
useEffect(()=> {
navigator.geolocation.getCurrentPosition(position =>{
userLat =
position.coords.latitude
;
userLong =
position.coords.longitude
;
console.log(userLat, userLong);
})
},[]);
return (
<div className="pt-5 justify-content-center align-items-center d-flex w-100"
style={{
backgroundSize: "cover",
height: "100vh",
}}
>
<GoogleMap
center={center}
zoom={15}
mapContainerStyle={{width: "80%", height:"80%"}}
onLoad={map=>setMap(map)}
</GoogleMap>
**<button onClick={()=> map.panTo(test)}>Pan Location</button>**
</div>
);
};
export default AddSpotPage;
Heres the code that worked for me:
const[userLat, setUserLat]= useState();
const[userLong, setUserLong]= useState();
useEffect(()=> {
navigator.geolocation.getCurrentPosition(position =>{
setUserLat(position.coords.latitude);
setUserLong(position.coords.longitude);
console.log(userLat, userLong);
})
},[]);
return(
<>
<GoogleMap
center={center}
zoom={15}
mapContainerStyle={{width: "80%", height:"80%"}}
onLoad={map=>setMap(map)}
>
</GoogleMap>
<button onClick={()=> map.panTo({lat:userLat,lng:userLong})}>Pan Location</button>
</>