Delivery Dashboard.3 (google map), painting Direction

김종민·2022년 10월 10일
0

Nuber-Client

목록 보기
20/21

들어가기
현재 위치에서 찍혀지는 위치로 지도에 그림그려주는것,
geocoder는 좌표를 주소로, 주소를 좌표로 만들어줌.


1. src/pages/driver/dashboard.tsx


import React, { useEffect, useState } from 'react'
import GoogleMapReact from 'google-map-react'

interface ICoords {
  lat: number
  lng: number
}

interface IDriverProps {
  lat: number
  lng: number
  $hover?: any  ///지도안에 자동차 그림을 넣는 component에 반드시 들어가야
                ///error가 생기지 않음.
}

///지도안에 자동차 그림을 넣어주기 위한 component.
///바로 div로 넣으면, console에 error가 나서, component로 넣어주어야 함.
const Driver: React.FC<IDriverProps> = () => <div className="text-lg">🚚</div>

export const Dashboard = () => {
  const [driverCoords, setDriverCoords] = useState<ICoords>({ lat: 0, lng: 0 })
  ///현재 위치를 저장하기 위해, state를 만들어줌.
  
  const [map, setMap] = useState<google.maps.Map>()
  ///현재 map을 저장해 주는 state
  const [maps, setMaps] = useState<any>()
  ///maps를 저장해 주는 state
  
  ///밑의 watchPosition을 실행시키기 위해서는 onSuccess와 onError이
  ///필요해서 만들어줌.
  ///watchPosition은 현재 위치를 모니터링 해줌.
  const onSuccess = ({
    coords: { latitude, longitude },
  }: GeolocationPosition) => {
    setDriverCoords({ lat: latitude, lng: longitude })
  }
  ///onSuccess로 현재 위치를 serDriverCoords에 위도, 경도를 넣어줌.
  const onError = (error: GeolocationPositionError) => {
    console.log(error)
  }
  useEffect(() => {
    navigator.geolocation.watchPosition(onSuccess, onError, {
      enableHighAccuracy: true,
    })
  }, [])
  ///useEffect를 이용해서 watchPosition을 실행시켜줌.
 
 ///여기서부터는 geocoder로 현재의 위도, 경도로 그 위도, 경도의 주소를 
 ///console에 찍어줌
  useEffect(() => {
    if (map && maps) {
      map.panTo(new google.maps.LatLng(driverCoords.lat, driverCoords.lng))
      const geocoder = new google.maps.Geocoder()
      geocoder.geocode(
        {
          location: new google.maps.LatLng(driverCoords.lat, driverCoords.lng),
        },
        (result, status) => {
          console.log(result, status)
        }
      )
    }
  }, [driverCoords.lat, driverCoords.lng])

  ///GoogleMapReact component에 들어갈 함수를 만들어줌.
  ///map은 사용되는 map이고, maps는 map에 사용될 함수의 집함.
  ///panTo는 User의 위치가 변할때마다, 지도의 center를 User의
  ///위치로 바꾸어준다.
  const onApiLoaded = ({ map, maps }: { map: any; maps: any }) => {
    map.panTo(new google.maps.LatLng(driverCoords.lat, driverCoords.lng))
    setMap(map)
    setMaps(maps)
  }
  
  ///버튼 클릭시, 주어진 위치로 길을 지도위에 그려줌.
  ///여기서는 현재 위치에서 위도+0.01, 경도+0.01의 위치로 이동하게 함.
  ///(지도에 그림이 그려지게 함)
  const getRouteClick = () => {
    if (map) {
    ///directionsService와 directionsRenderer를 이용해야 함.
      const directionsService = new google.maps.DirectionsService()
      const directionsRenderer = new google.maps.DirectionsRenderer()
      
      directionsRenderer.setMap(map)
      
      ///directionsRenderer에 setMap에 현재 map을 넣어줌.
      ///밑에 directionsService로 현재 위치과 이동될 위치를 찍어줌
      directionsService.route(
        {
          origin: {
            location: new google.maps.LatLng(
              driverCoords.lat,
              driverCoords.lng
            ),
          },
          ///origin은 현재위치
          
          destination: {
            location: new google.maps.LatLng(
              driverCoords.lat + 0.01,
              driverCoords.lng + 0.01
            ),
          },
          ///destination은 이동되는 위치
          
          travelMode: google.maps.TravelMode.TRANSIT,
          ///travelMode는 여러가지가 있는데, 한국은 TRANSIT밖에
          ///적용이 않됨 ㅠㅠ(카카오맵을 이용해야 할듯)
          
        },
        (result, status) => {
          directionsRenderer.setDirections(result)
        }
        ///마지막은 callback함수로 위와갑이 작성해줌.
      )
    }
  }
  return (
    <div>
      <div style={{ height: '70vh', width: '100%' }}>
        <GoogleMapReact
          yesIWantToUseGoogleMapApiInternals
          onGoogleApiLoaded={onApiLoaded}
          bootstrapURLKeys={{ key: 'AIzaSyCQBuKy-bkomVZm4BTMYc30cCDvtCpateI' }}
          defaultCenter={{
            lat: 35.166535,
            lng: 126.9779692,
          }}
          defaultZoom={15}
        >
          <Driver lat={driverCoords.lat} lng={driverCoords.lng} />
        </GoogleMapReact>
      </div>
      <button onClick={getRouteClick}>Get Route</button>
    </div>
  )
}

NOTICE!!!
구글맵사용은 처음 접해보는 것이라서 매우 어려워 보이므로
해야할거는 복습, 또 복습!!!!
주소를 위도,경도로 위도,경도를 주소로 바꿔주는 geocoder는
시간 날때, 꼭 다시 복습해 볼것!!!!

profile
코딩하는초딩쌤

0개의 댓글