Google Map Api 사용

LSM ·2021년 7월 22일
0

1. LG soft India 프로젝트 진행 중 도착지와 목적지를 받고 해당 위치의 경도와 위도를 DB에 저장해야할 일이 생김.

2. GoogleApi를 사용하여 이를 해결하고자 함

3. React hooks를 base로 하여 작성함.

4. 준비물 Google map platform api key.

5. 모듈 설치 : npm install --save google-map-react

소스코드

//index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';


ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

//App.js
import React, { useState } from "react";
import GoogleMap from "google-map-react";
import SearchBox from "./SearchBox";
import "./App.css";

const App = (props) => {
  const [apiReady, setApiReady] = useState(false);
  const [map, setMap] = useState(null);
  const [googlemaps, setGooglemaps] = useState(null);
  const [center, setCenter] = useState({ lat: 37.5, lng: 127 });
  let zoom = 10;

  if (window.screen.width >= 768) {
    zoom = 15;
  }

  const handleApiLoaded = (map, maps) => {
    if (map && maps) {
      setApiReady(true);
      setMap(map);
      setGooglemaps(maps);
    }
  };
  return (
    <div style={{ height: "100vh" }}>
      {apiReady && googlemaps && <SearchBox mapApi={googlemaps} />}
      <div className="googleMap">
        <GoogleMap
          bootstrapURLKeys={{
            key: "사용자 API KEY",
            libraries: "places",
          }}
          defaultCenter={center}
          defaultZoom={zoom}
          yesIWantToUseGoogleMapApiInternals
          onGoogleApiLoaded={({ map, maps }) => handleApiLoaded(map, maps)}
        ></GoogleMap>
      </div>
    </div>
  );
};

export default App;

//SearchBox.js
import React, { useCallback, useRef, useEffect } from "react";
const SearchBox = ({ mapApi }) => {
  const input = useRef(null);
  const searchBox = useRef(null);

  const handleOnPlacesChanged = useCallback(() => {
    console.log(searchBox.current.getPlaces());
    const places = searchBox.current.getPlaces();
    if (places) {
      console.log(
        places[0].geometry.location.lat(),
        places[0].geometry.location.lng()
      );
    }
  }, [searchBox]);

  useEffect(() => {
    if (!searchBox.current && mapApi) {
      searchBox.current = new mapApi.places.SearchBox(input.current);
      searchBox.current.addListener("places_changed", handleOnPlacesChanged);
    }

    return () => {
      if (mapApi) {
        searchBox.current = null;
        mapApi.event.clearInstanceListeners(searchBox);
      }
    };
  }, [mapApi, handleOnPlacesChanged]);

  return <input ref={input} placeholder="SearchBox" type="text" />;
};
export default SearchBox;

결과

profile
개발 및 취준 일지

0개의 댓글