Skip to content

Instantly share code, notes, and snippets.

@raldred
Last active November 5, 2017 13:42
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save raldred/b08cf60712eb87d81f05437444dff4ae to your computer and use it in GitHub Desktop.
Save raldred/b08cf60712eb87d81f05437444dff4ae to your computer and use it in GitHub Desktop.
Location Component for react native with workaround for Android issue https://github.com/facebook/react-native/issues/7495
export default class Location extends Component {
constructor(props) {
super(props);
this._locationReceived = false;
this._locationWatchID = null;
};
componentDidMount() {
this._locationReceived = false;
if(Platform.OS == 'android' && Platform.Version >= 23)
this._getInitialAndroid23Location();
else
this._getInitialLocation();
}
_getInitialAndroid23Location = async () => {
try {
console.log('Asking for location permission');
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
'title': 'Location',
'message': 'Access to your location ' +
'for some reason.'
}
)
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log('Location granted');
this._getInitialLocation();
} else {
console.log("Location permission denied")
}
} catch (err) {
console.warn(err)
}
};
_getInitialLocation = () => {
navigator.geolocation.getCurrentPosition((position) => {
this._setLocation(position);
},
(error) => {
console.log(JSON.stringify(error));
// this.setState({currentLocation: null});
},
{
enableHighAccuracy: false,
timeout: 20000,
maximumAge: 1000
}
);
if(Platform.OS == 'android' && !this._locationReceived)
{
this._locationWatchID = navigator.geolocation.watchPosition((position) => {
this._setLocation(position);
navigator.geolocation.clearWatch(this._locationWatchID);
});
}
};
_setLocation = (position) => {
this._locationReceived = true;
console.log("log location", position.coords);
// do something with the location
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment