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 editor and add below code into it into

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;  ?>

jQuery Datatable add date range filter

jQuery Datatable add date range filter Datatable is most useful jQuery plugin that helps to make our html tables more powerful and give powers to user to filter , search, sort, pagination etc, But Data table provides a common filter only and yes we can customize and add filter for each column, but still sometimes we need an advance filter like show results only between a date range, So today we will learn how to create a minimum and maximum date range fields and show date picker on it, and user can fill dates by selecting dates and data table will auto filter records based on it. Keep follow below steps :- I am using Bootstrap if you want to use any other framework then you can use. Create a new index.php file  and paste below code in it, i have used all required CDN like bootstrap, datatable, datepicker etc. <!DOCTYPE html> <html> <head>     <title>Datatable Date Range Filter Example</title>     <link rel="stylesheet" href="https://maxcd