구현하려는 내용
상태변수 place로 검색할 장소를 받아와, 구글맵에 마커로 표시
사용자 인증 정보 만들기
에서 API 키 애플리케이션 제한사항 설정 '없음'으로 생성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;