Hi Ivan,
I'm having some trouble getting the map to center on a user's geolocation upon initial rendering.
I receive a console error of:
GoogleMap: center or defaultCenterproperty must be defined
My implementation of this is in a component realData:
export function getLocation() {
let myLatLng = {
lat: 49.2527,
lng: -123.1207
};
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
myLatLng = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
// console.log("this is myLatLng" + myLatLng.toString());
console.log("return value of if cond");
console.log(myLatLng);
return myLatLng;
})
} else {
//browser doesn't support geolocation, set as vancouver
console.log("return value of else cond");
console.log(myLatLng);
return myLatLng;
}
}
and then in component GMap I have this import statement:
import { getLocation } from './data/realData'
then within googleMapHOC -->
withState(
'mapProps',
'setMapProps',
{
center: getLocation(),
zoom: 12,
}
),
some more info: my console.logs produce this output
GoogleMap: center or defaultCenterproperty must be defined
bundle.js:21143 [HMR] connected
bundle.js:20970 return value of if cond
bundle.js:20971 Object {lat: 49.2768856, lng: -123.0876059}
any help would be hugely appreciated.
cheers!
center: getLocation(), in your case returns undefined as navigator.geolocation.getCurrentPosition((position) => { is an asynchronous call, so you have undefined center at first rendering
was hoping it wasnt an async issue, I'll table this for now and post a solution when I figure it out.
Thanks Ivan :+1:
Sorry forgot to post my solution here (for anyone else interested)
In Layout (or parent of Gmap component:
constructor() {
super();
this.state = {
/// defaulted at vancouver
myLatLng: {
lat: 49.2827,
lng: -123.1207
}
};
}
getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
this.setState({
myLatLng: {
lat: position.coords.latitude,
lng: position.coords.longitude
}
}
);
})
} else {
//browser doesn't support geolocation, set as vancouver
this.setState({
myLatLng: {
lat: 49.8527,
lng: -123.1207
}
}
);
}
}
<GMap myLatLng={this.state.myLatLng} />cheers
hey! i keep receiving current location- undefined ... i tried a few version - also this solution, and similar ones that were published along the way here.. any idea maybe what the source for the undefined? 馃槪many thanks!
Most helpful comment
Sorry forgot to post my solution here (for anyone else interested)
In Layout (or parent of Gmap component:
<GMap myLatLng={this.state.myLatLng} />cheers