google map api에 대해 내가 쓴 글

https://fullfish.tistory.com/111

[구글 맵 API

https://console.cloud.google.com/google/maps-apis/start?hl=ko Google Cloud Platform 하나의 계정으로 모든 Google 서비스를 Google Cloud Platform을 사용하려면 로그인하세요. accounts.google.com 우선 해..

fullfish.tistory.com](https://fullfish.tistory.com/111)

위 게시물의 기본적인 코드는 지정된 경도 위도값만을 불러오는것인데

현재 프로젝트에서의 구글맵의 쓰임새는

가계부 작성시 자동으로 gps값이 db에 저장되며

나중에 해당 가계부 조회시 물건을 산 장소을 알 수 있게끔 하는것이다

그러므로

가계부 페이지 접속시 현재 경도, 위도값을 세션스토리지에 저장

-> 가계부 작성시 세션스토리지에 있는 경도, 위도값을 db로 송신

-> 가계부 열람시 db에서 경도, 위도값을 가져와서 구글 맵 api 불러올때 사용

의 순서를 따른다

로컬스토리지가 아닌 세션스토리지를 쓰는이유는

로컬스토리지는 영구적으로 보존되기에 직접 삭제를 해줘야 삭제가 되며

세션스토리지는 탭을 닫으면 삭제가 됩니다

gps는 유동적인 데이터라 세션스토리지에 저장했습니다

현재 경도, 위도는

function getLocation() {
  if (navigator.geolocation) {
    // GPS를 지원하면
    navigator.geolocation.getCurrentPosition(
      function (position) {
        sessionStorage.setItem('latitude', position.coords.latitude);
        sessionStorage.setItem('longitude', position.coords.longitude);
      },
      function (error) {
        console.error(error);
      },
      {
        enableHighAccuracy: false,
        maximumAge: 0,
        timeout: Infinity,
      },
    );
  } else {
    alert('GPS를 지원하지 않습니다');
  }
}

크롬에서 지원하면 해당 함수를 사용했습니다

position값을 받아온다면

세션스토리지에 각각 ‘latitue’와 ‘longitude’로 저장했습니다

그리고 map을 띄우는 코드는

import { Helmet } from 'react-helmet';
import React, { useRef, useState, useEffect } from 'react';
function Map({ gps }) {
  const gpsArray = gps.split(',');
  const latitude = gpsArray[0];
  const longitude = gpsArray[1];
  return (
    <>
      <div id="googleMap" style={{ width: '100%', height: '25vw' }}></div>
      <Helmet>
        <script>
          {`function myMap() {
        var mapOptions = {
          center: new google.maps.LatLng(
            ${latitude},
            ${longitude},
          ),
          zoom: 17,
        };

        var map = new google.maps.Map(
          document.getElementById('googleMap'),
          mapOptions,
        );
      }`}
        </script>
        <script src="https://maps.googleapis.com/maps/api/js?key=여기 api키 입력&callback=myMap"></script>
      </Helmet>
    </>
  );
}
export default Map;

처럼 경도 위도는 db에서 받아온 값을 썼다

참고 : Helmet은 html내에서

    <script src="https://maps.googleapis.com/maps/api/js?key=여기 키값넣기&callback=myMap"></script>
  </Helmet>
</>   ); } export default Map; ```