프론트/React Native, React

[리액트 네이티브] react-native 위도 경도를 주소로 변환 역 지오로케이션(expo)

연지양갱 2023. 7. 8. 21:55
728x90
반응형
SMALL

1. 아래 링크에서 회원가입 / 로그인한다

https://www.bigdatacloud.com/docs/api/reverse-geocode-to-city-api

 

Reverse Geocoding to City API

Returns detailed locality information for provided Latitude/Longitude coordinates

www.bigdatacloud.com

2. API패키지에서 map API key를 생성한다.

3. 위 링크에서 값을 reqeust, response해주면 주소를 가져올 수 있다.

4. request는 위도, 경도, api 키 값을 보내주면 된다

5. response 값으로는 위 코드에서 확인하면 된다. (엄청 많음!!)

 


 

컴공이나 개발 프로젝트를 진행하면서 지도 api나 라이브러리를 사용할 때가 있을 텐데 위도 경도값을 알아야 할 때가 많았을 것이다

 

내가 했던 프로젝트에서 역 지오로케이션을 사용하는 기능은

산책 경로를 리뷰할 때 사용했는데

했던 산책 경로를 입력하면 위도 경도값을 가지고 주소로 변환해야 했다

 

station의 위도 경도를 알면

당연히 주소도 알아야하니까 넣은 api이다..

지오로케이션의 반대라

위도 경도를 입력하면 주소로 변환하여 데이터 베이스에 저장한다.

 

참고

https://coding-dahee.tistory.com/172

 

[React Native] 날씨 API, 역지오코딩(위도/경도 > 주소), 미세먼지 API

1. 날씨 API https://home.openweathermap.org/api_keys Members Enter your email address and we will send you a link to reset your password. home.openweathermap.org api key 확인하고~ 위도 경도 필요해 https://coding-dahee.tistory.com/171 [React Na

coding-dahee.tistory.com

google map api가 있지만

복잡해서

무료인걸로 사용할 것이다아ㅏ

전에 해봤는데 어려웠다요,,,, 사실 기억도 안나지만ㅎ

 

 

https://www.bigdatacloud.com/docs/api/reverse-geocode-to-city-api

 

Reverse Geocoding to City API

Returns detailed locality information for provided Latitude/Longitude coordinates

www.bigdatacloud.com

  1. 회원가입
  2. api 패키지에서 Reverse Geocoding to city API 검색
  3. 여기에서 나온거 그냥 그대로 사용하면 됨

 

전에 날씨 api를 가져온 것 처럼

https://gamza1013.tistory.com/32

 

[리액트네이티브] react-native 날씨 가져오기(Expo)

앱에서 만드는 부분은 산책이라 ​ 날씨 api를 넣어야겠다고 생각함 ​ 그래서 ​ 날씨 api를 쓰려고 한다 ​ ​ https://velog.io/@yhko1992/%EB%82%A0%EC%94%A8-%EC%A0%95%EB%B3%B4-%EB%B0%9B%EC%95%84%EC%98%A4%EA%B8%B0

gamza1013.tistory.com

 

 

1. API_Key를 생성하여 변수에 저장

//api키
const API_KEY = "API_KEY"

 

2. 이벤트 발생하는 함수 내에 async await를 사용하여 request해준다

아래 코드는 화면이 보여줬을 때 실행 되는 useEffect안에 넣었다async await 비동기 함수도 사용해주는 것이 좋다

 

useEffect(() => {
        (async () => {
            // firebase
            try {
                //위치 수집 허용하는지 물어보기
                let { status } = await Location.requestForegroundPermissionsAsync();
                if (status !== 'granted') {
                    setErrorMsg('Permission to access location was denied');
                    return;
                }
            	// 사용자의 위치의 주소값 가져오기
                // 날씨 api에서는 response값 중에 사용자 주소값도 가져올 수 있다
                let location = await Location.getCurrentPositionAsync({});
                let addresscheck = await Location.reverseGeocodeAsync(location.coords);
                
                // 위도, 경도, api_key로 해당 주소값 가져올때 
                // Reqeust 부분
                const response = await fetch(`https://api-bdc.net/data/reverse-geocode?latitude=${위도}&longitude=${경도}&localityLanguage=en&key=${API_KEY}`);
                // Response 부분
                const res = await response.json()
                // 원하는 주소 내용만 가져오면 된다.
                console.log(res.localityInfo.administrative[0].name)
                console.log(res.localityInfo.administrative[4].name)
            } catch (error) {
                console.log('eeerror', error.message)
            }
        })();
    }, [])

주석 처리한 부분을 읽어보면 알 수 있을 것이다

 

공식 문서에서 나온 response값들은 

{
  "latitude": -34.93129,
  "longitude": 138.59669,
  "continent": "Australian continent",
  "continentCode": "AU",
  "localityLanguageRequested": "en",
  "city": "Adelaide",
  "countryName": "Australia",
  "countryCode": "AU",
  "postcode": "5000",
  "principalSubdivision": "South Australia",
  "principalSubdivisionCode": "AU-SA",
  "plusCode": "4QQW3H9W+FM",
  "locality": "Adelaide",
  "localityInfo": {
    "LikelyLand": true,
    "administrative": [
      {
        "name": "Australia",
        "description": "country in Oceania",
        "order": 1,
        "adminLevel": 2,
        "isoCode": "AU",
        "wikidataId": "Q408",
        "geonameId": 2077456
      },
      {
        "name": "South Australia",
        "description": "state of Australia",
        "order": 4,
        "adminLevel": 4,
        "isoCode": "AU-SA",
        "wikidataId": "Q35715",
        "geonameId": 2061327
      },
      {
        "name": "Adelaide City Council",
        "description": "local government area in South Australia",
        "order": 7,
        "adminLevel": 6,
        "wikidataId": "Q1094063",
        "geonameId": 7839644
      },
      {
        "name": "Adelaide",
        "description": "suburb of Adelaide, South Australia",
        "order": 8,
        "adminLevel": 9,
        "wikidataId": "Q4681820",
        "geonameId": 11523825
      }
    ],
    "informative": [
      {
        "name": "Australian continent",
        "description": "continent in the Earth's Southern Hemisphere",
        "order": 2,
        "isoCode": "AU",
        "wikidataId": "Q3960"
      },
      {
        "name": "Australia/Adelaide",
        "description": "time zone",
        "order": 3
      },
      {
        "name": "Adelaide",
        "description": "capital city of South Australia",
        "order": 5,
        "wikidataId": "Q5112",
        "geonameId": 2078025
      },
      {
        "name": "5000",
        "description": "postal code",
        "order": 6
      }
    ]
  }
}

이렇게 있다. 필요한 내용을 정제해서 set해주면 될것 같다

 

코드 수행해보고 위도, 경도, api key를 가지고 reqeust가 성공하면

위 내용이 나올 것이고, 오류가 생긴다면 공식 문서에서 error 내용을 확인해보면 좋을 것 같다

 

 

반응형