Skip to content

Instantly share code, notes, and snippets.

@xardit
Last active May 14, 2019 06:32
Show Gist options
  • Save xardit/5466f7309752cbb2e63ecefff6365bb9 to your computer and use it in GitHub Desktop.
Save xardit/5466f7309752cbb2e63ecefff6365bb9 to your computer and use it in GitHub Desktop.
gps.js - a react component for getting a promise of GPS coordinates for iOS and Android
/*
* Get GPS coordinates promise for Android and iOS
* This React Native component fixes the particular error that comes from Android: "location request timed out"
* @author a3diti
* 0x332D7E58
USAGE:
import getCoordinates from './gps'
getCoordinates().then(position => {
const coordinates = position.coords.latitude+','+position.coords.longitude
Alert.alert(coordinates)
}).catch(error => {
Alert.alert(error.message)
})
*/
import { PermissionsAndroid, Platform } from 'react-native'
const requestPermission = () => {
if(Platform.OS === 'ios') return Promise.resolve(true)
return PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
'title': 'Duhen të drejtat për kordinatat GPS',
'message': 'Kto të dhëna duhen për të gjeneruar adresën tuaj'
}
).then(granted => {
if(granted === PermissionsAndroid.RESULTS.GRANTED) {
return Promise.resolve("You can use the location")
} else {
return Promise.reject("Location permission denied")
}
})
}
const getCoordinates = () => {
return requestPermission().then(ok => {
return new Promise((resolve, reject) => {
const options = Platform.OS === 'android' ? {enableHighAccuracy:true,timeout:5000}
: {enableHighAccuracy:true,timeout:5000,maximumAge:2000};
global.navigator.geolocation.getCurrentPosition(resolve, reject, options)
})
})
}
export default getCoordinates
@Hassanjankhan
Copy link

Hassanjankhan commented May 14, 2019

componentDidMount = () => { var that = this; //Checking for the permission just after component loaded // that.checkLocationOnOff(); if (Platform.OS === 'ios') { this.callLocation(that); } else { async function requestLocationPermission() { try { const granted = await PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION, { 'title': 'Location Access Required', 'message': 'This App needs to Access your location' } ) if (granted === PermissionsAndroid.RESULTS.GRANTED) { //To Check, If Permission is granted // alert("granted") getCoordinates().then(position => { const coordinates = position.coords.latitude+','+position.coords.longitude alert(coordinates) }).catch(error => { alert(error.message) }) // that.callLocation(that); } else { alert("Permission Denied"); } } catch (err) { // alert("err",err); console.warn(err) } } requestLocationPermission();} }

promise return Request time out.
My location in on and set accuracy high
Any best soluation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment