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

Run and compile sass scss file to css using node

  Today we learn how to use scss and generate css using node  or Run and compile sass scss file to css using node   So please follow simple  steps :-   Today we will create a project that can read scss file and generates css with it  Note: Make sure you have installed node in your system. If you want to help to install node js based on your system then check our other tutorial or check node js official website. Now create a blank folder and open  terminal(linux) or cmd(windows) and navigate to your current project folder by using cd command Now run below command npm init after enter it will ask you some package info that you can fill according to you or just keep enter until it finished. The above command will generate package.json file Now  we will install npm module that will convert our scss to css Run below command: npm install node-sass So we have installed node-sass package . Now open package.json file in your...

How to retrieve Facebook Likes, share , comment Counts

function facebook_count($url){     // Query in FQL     $fql  = "SELECT share_count, like_count, comment_count ";     $fql .= " FROM link_stat WHERE url = '$url'";     $fqlURL = "https://api.facebook.com/method/fql.query?format=json&query=" . urlencode($fql);     // Facebook Response is in JSON     $response = file_get_contents($fqlURL);     return json_decode($response); } $fb = facebook_count('https://www.facebook.com/BahutHoGyiPadhai'); // facebook share count echo $fb[0]->share_count;  echo "like"; // facebook like count echo $fb[0]->like_count ; echo "comment"; // facebook comment count echo $fb[0]->comment_count;  ?>

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...