구글맵 API 사용

오서현·2023년 4월 27일
0

구현하려는 내용

상태변수 place로 검색할 장소를 받아와, 구글맵에 마커로 표시

1. API 키 생성

2. 확인해보기

3. 코드

import React, { useState, useEffect } from "react";
import { GoogleMap, Marker, useJsApiLoader } from "@react-google-maps/api";
import { API_KEY } from "../../config";

function Map({ place }) {

  const [center, setCenter] = useState({ lat: 37.5665, lng: 126.9780 });
  const [marker, setMarker] = useState(null);

  const containerStyle = {
    width: '100%',
    height: '100%',
  };

  const myStyles = [
    {
      featureType: "poi",
      elementType: "labels",
      stylers: [{ visibility: "off" }],
    },
  ];

  const { isLoaded } = useJsApiLoader({
    id: "google-map-script",
    googleMapsApiKey: API_KEY,
  });

  useEffect(() => {
    if (isLoaded) {
      const onSearch = () => {
        const geocoder = new window.google.maps.Geocoder();
        geocoder.geocode({ address: place }, (results, status) => {
          if (status === "OK") {
            setCenter({
              lat: results[0].geometry.location.lat(),
              lng: results[0].geometry.location.lng(),
            });
            setMarker({
              lat: results[0].geometry.location.lat(),
              lng: results[0].geometry.location.lng(),
            });
          } else {
            alert("Geocode was not successful for the following reason: " + status);
          }
        });
      };

      onSearch();
    }
  }, [place, isLoaded]);

  // window.google.maps 객체가 로드되지 않았을 때 처리
  if (!window.google || !window.google.maps) {
    return <div>Error loading Google Maps JavaScript API</div>;
  }

  return (
    <GoogleMap
      mapContainerStyle={containerStyle}
      center={center}
      zoom={15}
      options={{ disableDefaultUI: true, styles: myStyles }}
    >
      {marker && <Marker position={marker} />}
    </GoogleMap>
  );
}

export default Map;

0개의 댓글