Reputation: 77
My app only renders the initial value of my latitude/longitude state. I am trying to get it to render the updated state that I set to the users location with navigator.geolocation
. I've tried some conditional logic but I still only get a map with lat=0, lng=0. Here is my Map Component:
import React, { useState, useEffect } from "react";
import { GoogleMap } from "react-google-maps";
export default function Map() {
const [userLat, setUserLat] = useState(0);
const [userLng, setUserLng] = useState(0);
useEffect(() => {
function updateUserLat() {
//DIFFERENT CONDITIONS I'VE TRIED
// if (userLat === 0 && userLng === 0) {
// return;
// }
// if (userLat === 0 && userLng === 0) {
// return null;
// }
//function updateUserLat(latValue){if(!latValue) return;}
navigator &&
navigator.geolocation.getCurrentPosition(position => {
const coords = position.coords;
setUserLat(coords.latitude);
console.log(userLat);
});
return userLat;
}
function updateUserLng() {
//DIFFERENT CONDITIONS I'VE TRIED
// if (userLat === 0 && userLng === 0) {
// return;
// }
// if (userLat === 0 && userLng === 0) {
// return null;
// }
//function updateUserLng(lngValue){if(!lngValue) return;}
navigator &&
navigator.geolocation.getCurrentPosition(position => {
const coords = position.coords;
setUserLng(coords.longitude);
console.log(userLng);
});
return userLng;
}
updateUserLat();
updateUserLng();
}, [userLat, userLng]);
return (
<GoogleMap
defaultZoom={10}
defaultCenter={{ lat: userLat, lng: userLng }}
/>
);
}
Here is my App Component:
import React from "react";
import {
withScriptjs,
withGoogleMap
} from "react-google-maps";
import Map from "./Map";
const MyMapComponent = withScriptjs(withGoogleMap(Map));
export default function App() {
return (
<div style={{ width: "100vw", height: "100vh" }}>
<MyMapComponent
googleMapURL={`https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places&key=API_KEY
`}
loadingElement={<div style={{ height: `100%` }} />}
containerElement={<div style={{ height: `100%` }} />}
mapElement={<div style={{ height: `100%` }} />}
/>
</div>
);
}
Upvotes: 0
Views: 80
Reputation: 1226
you are not using useEffect()
correctly
your useEffect function are updating userLang
and userLat
, right ?
and userLang
and userLat
are states can only be changed by setUserLang
so if you need to trigger your useEffect you need to give it something that has changed in order to set the new userLat
useEffect(()=>{myfunction(){}
myFuncion();
},[thisVarActuallyChanges])
thisVarActuallyChanges
is a variable that changes in order to re-trigger useEffect
for more clarfication watch Ben Awad 's video about useEffect link
Upvotes: 2