본문 바로가기
안드로이드 웹앱 콘테츠 개발자 양성(국비지원)/HybridApp

HybridApp-React Native 2세대 (기능 - Geolocation API )

by 차누감 2020. 1. 29.

<최종 화면>

퍼미션을 추가하고 Geolocation을 이용하여 위도, 경도 정보를 알아오자.  

 


init 하기 전에 AVD를 켜놓자.

작업할 공간까지 접근하여 RN18Geolocation을 init 하자.

해당 사이트를 들어가서 사용 방법을 알아보자.

https://facebook.github.io/react-native/docs/geolocation.html

 

React Native · A framework for building native apps using React

A framework for building native apps using React

facebook.github.io

아래 사진의 설명을 읽어보면 대략 안드로이드에서는 android.location API를 사용하고

React Native에서는 Google Location Services API를 쓰란다. 

깃허브 주소를 보면 install등 사용방법등이 나오니 참고하자.

이제 install을 해보자.

install을 했다면 우선 run하자.

 

 

버튼을 누르면 화면에 위도, 경도 값을 보여주자.

위도, 경도를 주려면 퍼미션을 줘야 한다.

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

퍼미션을 적용하기 위해 다시 run을 해주자.

그러나 아직도 GET MY LLOCATION버튼이 에러다.

이유는 동적 퍼미션도 줘야된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import React, {Component} from 'react';
import {View, Text, Button, StyleSheet, PermissionsAndroid} from 'react-native';
 
import Geolocation from 'react-native-geolocation-service';
 
export default class Main extends Component{
 
    constructor(){
        super();
        this.state={
            currPos:{latitude: 0.0, longitude:0.0}, //최초 좌표객체[위도,경도]
        }
    }
    render(){
        return(
            <View style={{flex:1, padding:16,}}>
                {/* 1) 현재 내 위치 한번 얻어오기 */}
                <Button title="get my location" onPress={this.clickBtn}></Button>
 
                {/* 2) 내 위치 실시간 업데이트 */}
                <View style={{flexDirection:'row', marginTop:16, justifyContent:'space-between'}}>
                    <Button title="watch my location" color="green"></Button>
                    <Button title="stop my location" color="red"></Button>
                </View>
 
                <View style={{flex:1, justifyContent:'center', alignItems:'center',}}>
                    <Text style={{fontWeight:'bold',fontSize:20,padding:8}}>latitude : {this.state.currPos.latitude}</Text>
                    <Text style={{fontWeight:'bold',fontSize:20,padding:8}}>longitude : {this.state.currPos.longitude}</Text>
                </View>
            </View>
        );
    }
 
    clickBtn=()=>{
        // Geolocation객체에게 현재위치 얻어오기[web의 코드와 거의 비슷]
        Geolocation.getCurrentPosition( (position)=>{
            // 성공했을때 실행되는 영역
            // 파라미터로 받은 info객체 안에 좌표객체 정보 있음.
            this.setState({currPos: position.coords});
        }, 
        (error)=>{
            // 퍼미션이 없으면 에러!!! AndroidManifest.xml에서 추가
            // API 26버전부터 동적 퍼미션이 추가됨.
            // Geolocation은 동적퍼미션을 자동으로 해주지 않음
            alert('error : '+error.message);
        });
    }//clickBtn method...
 
    // 동적 퍼미션/////////
    async requestLocationPermission(){
            
        try{
            // 퍼미션 요청 다이얼로그 보이기
            const granted=await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION);
 
            if(granted== PermissionsAndroid.RESULTS.GRANTED){
                alert('위치정보 사용을 허가하셨습니다.');
            }else{
                alert('위치정보 사용을 거부하셨습니다.\n앱의 기능사용이 제한됩니다.');
            }
 
        }catch(err){alert('퍼미션 작업 에러');}
 
    }
    //화면이 시작될때 퍼미션 받도록 라이프사이클 메소드 이용
    async componentDidMount(){
       await this.requestLocationPermission()
    }
}
 

<실행 화면> 동적 퍼미션을 주고 버튼을 누르면 동작한다.

녹색 버튼과 적색 버튼의 기능을 하도록 코딩하자.


<실행화면>

Main.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import React, {Component} from 'react';
import {View, Text, Button, StyleSheet, PermissionsAndroid} from 'react-native';
 
import Geolocation from 'react-native-geolocation-service';
 
export default class Main extends Component{
 
    constructor(){
        super();
        this.state={
            currPos:{latitude: 0.0, longitude:0.0}, //최초 좌표객체[위도,경도]
        }
    }
    render(){
        return(
            <View style={{flex:1, padding:16,}}>
                {/* 1) 현재 내 위치 한번 얻어오기 */}
                <Button title="get my location" onPress={this.clickBtn}></Button>
 
                {/* 2) 내 위치 실시간 업데이트 */}
                <View style={{flexDirection:'row', marginTop:16, justifyContent:'space-between'}}>
                    <Button title="watch my location" color="green" onPress={this.clickBtn2}></Button>
                    <Button title="stop my location" color="red" onPress={this.clickBtn3}></Button>
                </View>
 
                <View style={{flex:1, justifyContent:'center', alignItems:'center',}}>
                    <Text style={{fontWeight:'bold',fontSize:20,padding:8}}>latitude : {this.state.currPos.latitude}</Text>
                    <Text style={{fontWeight:'bold',fontSize:20,padding:8}}>longitude : {this.state.currPos.longitude}</Text>
                </View>
            </View>
        );
    }
 
    clickBtn=()=>{
        // Geolocation객체에게 현재위치 얻어오기[web의 코드와 거의 비슷]
        Geolocation.getCurrentPosition( (position)=>{
            // 성공했을때 실행되는 영역
            // 파라미터로 받은 info객체 안에 좌표객체 정보 있음.
            this.setState({currPos: position.coords});
        }, 
        (error)=>{
            // 퍼미션이 없으면 에러!!! AndroidManifest.xml에서 추가
            // API 26버전부터 동적 퍼미션이 추가됨.
            // Geolocation은 동적퍼미션을 자동으로 해주지 않음
            alert('error : '+error.message);
        });
    }//clickBtn method...
    clickBtn2=()=>{
        // 기존에 warch하는 것이 있다면 지우도록!!
        Geolocation.clearWatch(this.state.id,); //만약 id가 없다면 무시됨
        const id=Geolocation.watchPosition((position)=>{
            this.setState({currPos: position.coords});
        },
        (error)=>{
            alert('error : '+error.message);
        });
 
        // watchID를 state에 저장하기
        //this.setState({id:id}); //새로이 id 프로퍼티 추가... 아래 코드로 간략화 가능
        this.setState({id}); //변수명과 키값이 같다면 변수명만 기입하면 키값은 자동 변수명으로 적용
 
    }//clickBtn2 method...
 
    clickBtn3=()=>{
        Geolocation.clearWatch(this.state.id,);
        this.setState({currPos:{latitude:0.0, longitude:0.0}});
    }//clickBtn3 method...
 
 
 
    // 동적 퍼미션/////////
    async requestLocationPermission(){
            
        try{
            // 퍼미션 요청 다이얼로그 보이기
            const granted=await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION);
 
            if(granted== PermissionsAndroid.RESULTS.GRANTED){
                alert('위치정보 사용을 허가하셨습니다.');
            }else{
                alert('위치정보 사용을 거부하셨습니다.\n앱의 기능사용이 제한됩니다.');
            }
 
        }catch(err){alert('퍼미션 작업 에러');}
 
    }
    //화면이 시작될때 퍼미션 받도록 라이프사이클 메소드 이용
    async componentDidMount(){
       await this.requestLocationPermission()
    }
}
 

댓글