Search code examples
react-nativepositiongetlocation

get current position in expo


I am building a project in react-native and i need to find my current location. My teacher told me to use Location.getCurrentPositionAsync. But the position I always find is: 37.421998333333335 - -122.084. because?

import React, { Component, useState} from 'react';
import {View, StyleSheet,Dimensions} from 'react-native';
import * as Location from 'expo-location';
import MapView from 'react-native-maps';
const { height } = Dimensions.get("window");

export default class TrainMap extends Component {
    constructor(){
        super();
        this.state={location:"",latitude:null,longitude:null}
    }
    async locationPermissionAsync() {
        let canUseLocation = false;
        const grantedPermission = await Location.getForegroundPermissionsAsync()
        if (grantedPermission.status === "granted") {
        canUseLocation = true;
        } else {
        const permissionResponse = await Location.requestForegroundPermissionsAsync()
        if (permissionResponse.status === "granted") {
        canUseLocation = true;
        }
        }
        if (canUseLocation) {
            const location = await Location.getCurrentPositionAsync(
                
            )
            console.log("received location:", location);
            this.state.location = location.coords.latitude + " - " + location.coords.longitude; 
            this.state.latitude=location.coords.latitude;
            this.state.longitude=location.coords.longitude;
        console.log("Position is: "+this.state.location)
        }
        }
        componentDidMount() {
            this.locationPermissionAsync() 
}; 
render(){}
}

how can i get my current location?


Solution

  • Ahh since youre using an android emulator, the lat long which youre getting is the default one which represents the where the emulator currently is at.

    YOu can change the lat long on emulator via How to emulate GPS location in the Android Emulator?

    check this blog

    Youll get an idea how to change, but rest assured in physical device youll get the updated lat long,

    enter image description here