Skip to main content

Location

安裝location

expo install expo-location

製作useLocation hook

import React,{useEffect} from 'react';
import {Text, StyleSheet, View, Button} from 'react-native';
import * as Location from 'expo-location';

const useLocation = () => {
const [location, setLocation] = useState();

const getLocation = async () => {
const {granted} = await Location.requestPermisionsAsync(); //get permission to get the user's current location
if(!granted) return; //if not granted, return nothing
const {coords:{latitude, longitude} } = await Location.getLastKnowPositionAsync(); //if granted, get the coordinates from the result
setLocation({latitude, longitude}); //save the coordinates into the location variable
}

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

return location;
}

export default useLocation;

使用useLocation hook

import React,{useEffect} from 'react';
import useLocation from '../hooks/useLocation';

function MyScreen = () => {
const location = useLocation();
return(
<Button title="" onPress={()=>console.log(location)} />
);
}