-
-
Save alexHlebnikov/3131f352eb255a79df1e25cb31d8a1f9 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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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