취업/React.JS
[React.js] 구글 맵 만들기.
카슈밀
2024. 3. 4. 14:14
반응형
간단한 지도 만들기 기능.
대략적인 기능은 chat gpt를 통해 만들었으나
세부 기능은 최신화가 되지 않아서 내가 만들어야 했다.
주소 검색에 따라 주소출력을 구현하여야만 했어 만들었다.
import React, { useState } from 'react'
import { GoogleMap, useJsApiLoader, MarkerF } from '@react-google-maps/api';
const containerStyle = {
width: '100vw',
height: '100vh'
};
const OPTIONS = {
minZoom: 4,
maxZoom: 18,
}
function Map() {
const { isLoaded } = useJsApiLoader({
id: 'google-map-script',
googleMapsApiKey: "구글 키",
libraries: ["places"],
})
const [map, setMap] = React.useState(null);
const [center, setCenter] = useState({
lat : 51,
lng : 24
});
const [markerPosition, setMarkerPosition] = useState(center);
const handleMapClick = async (event) => {
const point = {
lat: event.latLng.lat(),
lng: event.latLng.lng()
};
// 클릭한 위치로 마커 위치 변경
setMarkerPosition(point);
setCenter(point)
try {
const results = await geocodeLatLng({
lat: event.latLng.lat(),
lng: event.latLng.lng()
});
console.log("주소:", results[0].formatted_address);
} catch (error) {
console.error('Error fetching address', error);
}
};
// 지리적 좌표를 주소로 변환하는 함수
const geocodeLatLng = async (latLng) => {
const geocoder = new window.google.maps.Geocoder();
return new Promise((resolve, reject) => {
geocoder.geocode({ location: latLng }, (results, status) => {
if (status === 'OK') {
resolve(results);
} else {
reject(status);
}
});
});
};
const onLoad = React.useCallback(function callback(map) {
// This is just an example of getting and using the map instance!!! don't just blindly copy!
const bounds = new window.google.maps.LatLngBounds(center);
map.fitBounds(bounds);
setMap(map)
}, [])
const onUnmount = React.useCallback(function callback(map) {
setMap(null)
}, [])
return isLoaded ? (
<GoogleMap
mapContainerStyle={containerStyle}
center={center}
options={OPTIONS}
onLoad={onLoad}
onUnmount={onUnmount}
onClick={handleMapClick}
>
{/* 마커 */}
<MarkerF position={markerPosition} draggable={true} onDragEnd={(event) => setMarkerPosition(event.latLng.toJSON())} />
</GoogleMap>
) : <></>
}
export default React.memo(Map)
chat gpt의 경우 예전에 사용된 <Mark />로 제공하여 마커가 보이지 않는 문제가 있었다.
해당 기능을 역시나 동일하게 사용해서 안된다는 선구자들이 있어 해결하였다.
해당 내용을 겪은 자들이 push했던 문제일테니까.
https://stackoverflow.com/questions/72112491/marker-not-showing-react-google-maps-api-on-localhost-next-js
Marker not showing @react-google-maps/api on localhost next.js
I'm aware there are similar questions to this... but nothing has answered my question I'm trying to add a marker to my google map but it is not showing up when I'm running the project locally (It w...
stackoverflow.com
728x90