Expo get current location of a user
Expo is a very useful tool to create a mobile application using react native. it handles many complicated things like publish, generate certificates ,access camera , location etc.
To get the location of a user , we need to install expo-location package so to install it please open terminal/cmd in current project folder and run below command
expo install expo-location
above command will install expo location package. This package handles ask location permission, get long/lat details , get last location , current location etc.
How it works ?
To get access of user's current location we need to ask for permission to user by using Location.requestPermissionsAsync() function , this function will show a permission popup to user so user can allow it, If user reject it then we cannot get current location. Once user allow us to access location then we will use location package another function Location.getCurrentPositionAsync(), this function will return us an object that contains longitude and latitude, we need only this two values to get current position.
Code in action
First we will create a hook so we do not need to write code again and again. So create a new folder hooks in your current project main directory and create a new file in it useLocation.js, please use "use" as pretext in filename so react native will treat it as an hook.
File Location : CURRENT_PROJECT_FOLDER/hooks/useLocation.js
useLocation.js file Code
Now our hook is completed and we can access this in any screen. For this tutorial i am creating a new screen to show longitude and latitude values.
Create a screen TestScreen.js and import our hook in it by using below code
make sure your screen is not in any folder , if its in a folder then please use that file location.
Now i am using functional component so my code is like below
TestScreen.js file code
This will print users current location details like longitude and latitude. If you want to get users current address then pass this long lat details with google map API's and you can get it.
Thanks for reading :)
Related Links
React native get users long and lat details
Expo location how to ask permission for location
location permission prompt in android and ios using Expo
Comments
Post a Comment