본문 바로가기

Project/mevote

지도 api 사용 후기

0. 구현 과정

 

(1) 위도 경도 값을 받아옵니다. 
(2) 위도 경도 값을 주소로 변환합니다.
(3) 주소를 가지고 선거 API를 호출합니다. 

 

각각의 과정에서 비동기문제가 발생하여 이를 해결하는데 문제를 겪었다... 

 

1. 현재 위도 경도 받아오기

  • html5에서 제공하는 기본 wep api를 사용하면 된다. 
  • navigator.geolocation.getCurrentPosition()
  • sucess, error 두개의 콜백함수를 parameter로 받는다
const getLocation = () => {
  let latitude, longitude;
  if (navigator.geolocation) {
    // GPS를 지원하면
    navigator.geolocation.getCurrentPosition(
      function (position) {
        latitude = position.coords.latitude;
        longitude = position.coords.longitude;
        console.log('위도 : ' + latitude + ' 경도 : ' + longitude);
      },
      function (error) {
        console.error(error);
      },
      {
        enableHighAccuracy: false,
        maximumAge: 0,
        timeout: Infinity,
      },
    );
  } else {
    alert('GPS를 지원하지 않습니다');
    return;
  }
};
 

Geolocation.getCurrentPosition() - Web API | MDN

Geolocation.getCurrentPosition() 메서드는 장치의 현재 위치를 가져옵니다.

developer.mozilla.org

 

2. 위도 경도 값을 저장하고 사용하기

 

  • 이때 비동기문제로 인해 많은 버그가 발생했다. 비동기문제는 항상 어렵다.. async await 문법을 사용하여 이를 해결했다. 
  • 구현하고자 하는 것은 받아온 위도경도를 구글 Geocode API를 사용해서 주소로 변환하는 것이다. 이를 위해 위도, 경도 값을 파라미터로 넘겨줘야 하고 이 모든 상황을 비동기적으로 유연하게 처리하여야 한다. 
  • 또한 변환하여 얻은 주소를 다시 선거 API 호출시의 파라미터로 사용하고자 하였다. 
 

OKKY | 비동기처리 질문드립니다. (값을 리턴해주는 함수)

안녕하세요 위도/경도 값을 리턴해주는 함수를 만들고있는데요 제가 원하는대로 값만 리턴 시킬라면 어떻게 해야할지 모르겠어서 질문드립니다. promise로 함수를 리턴해서 다른 함수에서 then을

okky.kr

3. 비동기 문제 해결과정

 

geocoding.js : 위도경도를 받아와서 주소로 변환하기 까지의 과정입니다. 

import Geocode from 'react-geocode';

const getPos = () => {
  return new Promise((resolve, reject) => {
    navigator.geolocation.getCurrentPosition(resolve, reject);
  });
};

const getCoordinate = async () => {
  if (navigator.geolocation) {
    const position = await getPos();
    return {
      lat: position.coords.latitude,
      lon: position.coords.longitude,
    };
  } else {
    // Geolocation API에 액세스할 수 없으면 서울시청 좌표 리턴
    return {
      lat: 37.566353,
      lon: 126.977953,
    };
  }
};

const run = async () => {
  const { lat, lon } = await getCoordinate();
  Geocode.setApiKey('AIzaSyC5xLfDXfz6s9-soQmiQmLHms6QKeXjJ6s');
  Geocode.setLanguage('ko');
  Geocode.setRegion('es');
  Geocode.enableDebug();

  const address = await Geocode.fromLatLng(lat, lon).then((response) => {
    const address = response.results[0].formatted_address;
    console.log('현재 주소', address);
    return address.split(' ');
  });

  return address;
};

export default run;

 

useCandidate : 주소를 받아 선거 api를 호출합니다. 

import { useEffect, useState } from 'react';
import useAPI from './useAPI';
import getURL from './getURL';
import run from './geocoding';

function useCandidate(num) {
  const { customFetch } = useAPI();
  const [candidates, setCandidates] = useState();

  useEffect(() => {
    const fetchCandidate = async () => {
      const address = await run();
      console.log(address);
      const URL = getURL(num, address[1], address[2]); // 서울특별시, 마포구
      const json = await customFetch(URL);
      setCandidates([...json.getPofelcddRegistSttusInfoInqire.item]); 
    };
    fetchCandidate();
  }, []);
  return { candidates };
}

export default useCandidate;

 

4. 그 외 과정에서 겪은 문제 

 

처음에는 네이버 클라우드의 maps API를 사용하고자 했다. 하지만 CORS문제 및 response로 받아 온 응답 body가 스펙과 달라서 문제를 겪었고 구글의 Geocode API를 사용하는 것으로 변경했다.  

 

네이버 지도 API의 경우 호출 할때 적절한 서버주소를 필요로 했고 이를 위해 도메인을 구매하기도 해보고 package.json에서 proxi 옵션을 추가해보기도 했다. 하지만 결론적으로 적절한 response를 받아오는데에 실패했다. 프론트에서 사용하기 불친절한 네이버 지도 API였다...

 

Naver Geocoding API CORS 에러 해결

주소의 텍스트를 입력받아 좌표를 포함한 상세정보들을 제공하는 API 자세히axios로 Geocoding API를 호출하였는데 CORS 에러가 발생하였다. 1\. 아래와 같이 package.json에서 proxy 옵션을 설정한다.    

velog.io