Skip to main content

React native Expo get current location of a user

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

 
import { useEffect, useState } from "react";
import * as Location from "expo-location";

export default useLocation = () => {
  const [locationsetLocation= useState();

  const getLocation = async () => {
    try {
      const { granted } = await Location.requestPermissionsAsync();
      if (!grantedreturn;
      const {
        coords: { latitudelongitude },
      } = await Location.getCurrentPositionAsync();
      setLocation({ latitudelongitude });
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    getLocation();
  }, []);

  return location;
};


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

import useLocation from "./hooks/useLocation";

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

import React, { useEffect, useState } from "react";
import {
  Animated,
  FlatList,
  StyleSheet,
  View,
  Button,
  TouchableOpacity,
  Text,
from "react-native";
import useLocation from "./hooks/useLocation";]


function TestScreen() {
  const location = useLocation();
 
  return (
    <>
     <Text>{JSON.stringify(location)}</Text>
    </>
  );
}

export default TestScreen;



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

Popular posts from this blog

Convert website to android and ios application using react native expo webview

Convert website to android and ios application using react native expo webview If you want to check you can check on github by using below link also dont forget to give star ;) Source Code: https://github.com/shubham715/react-native-expo-webview-convert-website-to-app React native is the best choice to create multi platform mobile application , but sometimes we dont want to write a complete application because we already have a web application or a website and its complicated to manage both . So we have a solution for this problem. React native supports webView that makes easy to run any website url like an app natively. What is webview in react native? In React native, WebView helps to show web content in a native view. For this tutorial we will use EXPO. What is EXPO ? EXPO a set of tools to help you quickly start an app. Expo have many inbuilt components that helps to simplify the development and testing of React Native app. So please follow the below steps to c...

Solution-windows 'expo' is not recognized as an internal or external command

Solution for expo is not recognized as an internal or external command,operable program or batch file in Windows 10 Sometimes expo will not work globally mostly in windows 10, If you are facing same issue then follow the below Steps 1) Click on windows button and search for  " Environment variables"  and click on "Edit the system environment variables" 2) Now you will see a popup like below screen. Then you need to click on Environment Variables. (Please see highlight part in below image)     3)Then click on new button that i have highlighted in below image 4. Then a popup will open and you need to fill details like below mentioned Variable Name :Path Variable Value: %USERPROFILE%\AppData\Roaming\npm Here we are creating a new path variable and passing location of npm.   Now Click on OK and close all the terminal windows and open new CMD or terminal and type Expo . Great now you can access expo from any...

Read files from folder using php

Read files from folder using PHP Today we learn how to read all files from a folder . we will learn to list all files and read all files . So please follow below steps:-   METHOD 1 1) List all files from folder If you want the list of all files in a folder then you can do by using below code //Get a list of file paths using the glob function. $allFilesList= glob('myfolder/*'); //Loop through the array that glob returned. foreach($allFilesList as $filename){ //Simply print them out onto the screen. echo $filename; echo '<br>'; } The above code will print list of all files like file1.jpg file2.png file3.gif file4.pdf   If you want to read only specific extension file like you just want to a list of all png files then you can do it by using below code. //Get a list of all files ending in .txt $fileList = glob('myfolder/*.png);   METHOD 2 Here is the second method. here we are using scandir() function to s...