
현대 웹 애플리케이션에서 위치 기반 서비스의 중요성은 날이 갈수록 증가하고 있습니다. Google Maps API를 활용한 구현은 사용자에게 직관적이고 효율적인 인터랙션을 제공할 수 있습니다. 이 글에서는 Google Maps API와 React를 결합하여 실시간 위치 추적 및 경로 표시 기능을 갖춘 웹 애플리케이션을 개발하는 방법을 소개합니다.
React 애플리케이션에서 Google Maps를 사용하기 위해 google-map-react 라이브러리를 설치합니다. 이 라이브러리는 Google Maps API의 일부 기능을 React 컴포넌트로 쉽게 사용할 수 있게 해줍니다.
npm i google-map-react
npm i --save-dev @types/google-map-react
Google 지도를 사용하기 위해서는 API 키가 필요합니다. Google Cloud Platform에서 새 프로젝트를 생성하고 Maps JavaScript API를 활성화한 후, API 키를 생성합니다. 생성된 키는 요청할 때마다 사용되며, 필요에 따라 특정 HTTP 리퍼러에서만 사용하도록 제한할 수 있습니다.
navigator.geolocation.watchPosition 메소드를 사용하여 사용자의 위치가 변경될 때마다 새 위치 정보를 받아올 수 있습니다. 이 정보는 지도의 중심을 업데이트하는 데 사용됩니다.
navigator.geolocation.watchPosition(onSuccess, onError, {
enableHighAccuracy: true,
});
google-map-react 라이브러리를 사용하여 Google 지도를 렌더링하고, onGoogleApiLoaded 콜백을 통해 map 및 maps 객체에 접근하여 지도 제어 기능을 사용할 수 있습니다.
<GoogleMapReact
yesIWantToUseGoogleMapApiInternals
onGoogleApiLoaded={onApiLoaded}
defaultZoom={15}
defaultCenter={{ lat: driverCoords.lat, lng: driverCoords.lng }}
bootstrapURLKeys={{ key: "YOUR_API_KEY" }}
>
<Driver lat={driverCoords.lat} lng={driverCoords.lng} />
</GoogleMapReact>
Google Maps의 DirectionsService와 DirectionsRenderer를 사용하여 특정 위치 사이의 경로를 계산하고 지도에 표시할 수 있습니다. 이를 통해 사용자는 실시간으로 경로 변경을 확인할 수 있습니다.
const directionsService = new google.maps.DirectionsService();
const directionsRenderer = new google.maps.DirectionsRenderer();
directionsRenderer.setMap(map);
directionsService.route({
origin: { location: new google.maps.LatLng(driverCoords.lat, driverCoords.lng) },
destination: { location: new google.maps.LatLng(driverCoords.lat + 0.05, driverCoords.lng + 0.05) },
travelMode: google.maps.TravelMode.TRANSIT,
}, (result) => {
directionsRenderer.setDirections(result);
});
Google Maps와 React를 결합하면, 위치 기반 데이터를 처리하고 사용자에게 실시간 정보를 제공하는 강력한 웹 애플리케이션을 구축할 수 있습니다. 위의 방법을 통해 개발자는 더 나은 사용자 경험을 제공하고, 위치 기반 서비스의 효율성을 극대화할 수 있습니다.