Google Map APIの使用


1.LGソフトIndiaプロジェクトの進行中、宛先と宛先を受け取った後、その位置の経度と緯度をDBに保存する必要がある。


2.GoogleApiでこの問題を解決する


3.react hooksをベースに作成します。


4.準備物Google地図プラットフォーム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;

結果