[React] Google Maps API 사용하기 (2)

woodylovesboota·2023년 10월 13일
0
post-thumbnail

Google Maps API는 화면에 구글 지도를 출력해 주는 것 뿐만 아니라 다양한 기능을 제공해준다.

특정 장소를 검색하고 장소에 대한 정보를 얻어오는것 또한 가능하다.

Find Place

특정한 장소를 검색하는 API의 기본 형태는 다음과 같다.

https://maps.googleapis.com/maps/api/place/findplacefromtext/json?parameters

입력해주어야 하는 parameter는 두가지가 있다.

input : 검색하고싶은 장소
inputtype : 장소에 대해 필요한 정보

input 에는 검색하고 싶은 장소를 넣어주면 된다.
inputtype 에는 필요한 정보들을 요청하면 되는데 name, formatted_address, place_id, photos 등의 정보들을 요청할 수 있다. 자세한 사항은 공식문서 참고.

실제 API를 사용하여 보자.

export const getPlace = async (keyword: string | undefined) => {
  return await axios
    .get(
      `/maps/api/place/findplacefromtext/json?input=${keyword}&inputtype=textquery&fields=formatted_address%2Cplace_id%2Cphotos%2Cname%2Crating%2Cgeometry&key=${API_KEY}`
    )
    .then((res) => res.data);
};

useQuery hook을 이용하여 API를 호출한 후에

  const { data, isLoading } =
    useQuery<IPlace>(["getPlace", "place"], () =>
      getPlace("effel tower")
    );

결과를 화면에 나타내보자.

          <div>
            <h2>{data?.candidates[0].name}</h2>
            <h2>{data?.candidates[0].formatted_address}</h2>
            <h2>rating: {data?.candidates[0].rating}</h2>
            <h2>
              lat: {data?.candidates[0].geometry.location.lat}
            </h2>
            <h2>
              lng: {data?.candidates[0].geometry.location.lng}
            </h2>
            <h2>{data?.candidates[0].place_id}</h2>
          </div>

AutoComplete

Autocomplete은 검색어를 자동완성 해주는 API이다. 정확한 검색어를 입력하지 않아도 되며, 복수의 결과를 반환해 준다는 장점이 있다.

기본 형태는 다음과 같다.

https://maps.googleapis.com/maps/api/place/autocomplete/json?parameters

Find Place와 마찬가지로 검색어인 input을 포함해 주어야 하며 검색 결과를 한정하기 위해 검색 지역인 location 과 범위인 radius를 입력할 수 있다. .

export const getAutoCompletePlaces = async (
  keyword: string | undefined,
  location: string,
  radius: number
) => {
  return await axios
    .get(
      `/maps/api/place/autocomplete/json?input=${keyword}&location=${location}&radius=${radius}&key=${API_KEY}`
    )
    .then((res) => res.data);
};
  const { data, isLoading } =
    useQuery<IGeAutoCompletePlacesResult>(
      ["autocompletePlaces", "places"],
      () =>
        getAutoCompletePlaces(
          value,
          destination.geometry.location.lat +
          "%2C" +
          destination.geometry.location.lng,
          500
        )
    );

위에서 검색한 effel tower를 기준으로 500미터 반경의 개선문을 찾아보자

<ResultList>
  {data.predictions.map((place) => (

    <div>
      <h2>{place.structured_formatting.main_text}</h2>
      <h2>{place.description}</h2>
      <h2>{place.place_id}</h2>
    </div>
  ))}

Auto Complete API는 한정된 정보만을 제공한다. 공식문서에서는 장소의 더 detail한 정보를 얻고 싶다면 place_id를 이용하여 place detail API를 사용하는 것을 제안하고 있다.

Place Detail

Place Detail API는 Google map 에서 장소별로 제공하는 고유한 place_id를 이용하여 특정 장소의 세부 정보를 요청하는 API이다.

기본 형태는 다음과 같다.

https://maps.googleapis.com/maps/api/place/details/json?parameters

parameter에는 원하는 세부정보의 종류가 들어간다. opening hourdelivery 여부 등 다양한 정보를 요청할 수 있으니 자세한건 공식 문서를 참조하면 된다.

다음은 장소의 이름, rating, 리뷰, 전화번호, 주소, summary, 위치 좌표, 사진을 요청한 코드이다.

export const getPlaceDetail = async (id: string | undefined) => {
  return await axios
    .get(
      `/maps/api/place/details/json?fields=name%2Crating%2Creviews%2Cinternational_phone_number%2Cformatted_address%2Ceditorial_summary%2Cgeometry%2Cphotos&language=ko&place_id=${id}&key=${API_KEY}`
    )
    .then((res) => res.data);
};
  const { data, isLoading } = useQuery<IGetPlaceDetail>(
    ["getPlaceDetail",place_id],
    () => getPlaceDetail(place_id)
  );
<div>
  <div
    style={{
      backgroundImage: `url(${makeImagePath(
        data?.result.photos
        ? data?.result.photos[0].photo_reference
        : "",
        500
      )})`,
        width: "200px",
        height: "200px",
        backgroundPosition: "center center",
        backgroundSize: "cover",
    }}
    />
  <h2>{data.result.name}</h2>
  <h2>{data.result.formatted_address}</h2>
  <h2>{data.result.international_phone_number}</h2>
  <h2>{data.result.rating}</h2>
  <h2>{data.result.editorial_summary?.overview}</h2>
</div>

마치며

React에 Google Map API를 쓸 일이 생겨서 API 사용법을 정리해 보았다. js 나 ts를 이용하는 다른 예시들이 공식 문서에 소개되어 있지만 가장 범용적으로 쓰일 수 있는 방법을 익히는게 나중에 확장성 측면에서 좋을 것 같다.

0개의 댓글