출처: https://bumcrush.tistory.com/182 [맑음때때로 여름]

상세 컨텐츠

본문 제목

Google Map

React

by 장동균 2020. 8. 5. 15:30

본문

https://www.youtube.com/watch?v=Alz13kGluL8&t=1041s

https://github.com/jaewonhimnae/react-google-map/tree/master/src

 

jaewonhimnae/react-google-map

Contribute to jaewonhimnae/react-google-map development by creating an account on GitHub.

github.com

이 유튜브 강의와 github코드를 이용하였다. 정말 도움이 많이 되는 강의들 뿐이다. react를 처음 공부하는 사람들에게 여기 있는 강의들은 아주 큰 도움이 될거라 생각한다.

 

처음 강의를 다 듣고 나만의 todolist를 생각해봤다.

 

1. Hook으로 다시 만들어본다.

 

2. 내가 지정한 위치들을 db에 저장해서 따로 그것들만 불러오는 page를 하나 더 구축한다.

 

하지만...... 사실상 둘 다 성공하지 못했다.

 

google map api를 사용하는데 우리 같이 공부를 위한 목적이라면 돈이 들지 않는다. 하지만, visa 카드 등록이 필요한데 내가 visa카드가 없다. 그래서 내 나름대로 1번을 해보긴 했지만 google api로 부터 전송되는 데이터들을 받을 수가 없어서 잘 되었는지 정확한 확인은 어렵다... 그래도 오류 없이 compile되니까 잘 되지 않았을까...? 나중에 visa카드가 생기면 그때 다시 해봐야겠다.

 

import React, { useState } from "react";
import {
  InfoWindow,
  withScriptjs,
  withGoogleMap,
  GoogleMap,
  Marker,
} from "react-google-maps";
import Geocode from "react-geocode"; //위도와 경도를 통해 address,city 등등을 알기 위해 geocode를 사용
import { Descriptions } from "antd";
import AutoComplete from "react-google-autocomplete";
import { useEffect } from "react";

Geocode.setApiKey("AIzaSyCkOwp6R_g4uqLOW07GM"); //geocode를 쓰기 위해서는 setApiKey 과정이 필요

const LandingPage = () => {
  const [address, setAddress] = useState("");
  const [city, setCity] = useState("");
  const [area, setArea] = useState("");
  const [state, setState] = useState("");
  const [zoom, setZoom] = useState("");
  const [height, setHeight] = useState("");
  const [mapPosition, setMapPosition] = useState({ lat: 0, lng: 0 });
  const [markerPositon, setMarkerPosition] = useState({ lat: 0, lng: 0 });

  // 현재 사용자의 위치를 파악하기 위한 Geolocation API
  useEffect(() => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition((position) => {
        Geocode.fromLatLng(
          position.coords.latitude,
          position.coords.longitude
        ).then(
          (response) => {
            console.log(response);
            const address = response.results[0].formatted_address;
            const addressArray = response.results[0].address_components;
            setAddress(address);
            setCity(getCity(addressArray));
            setArea(getArea(addressArray));
            setState(getState(addressArray));
            setMapPosition({
              lat: position.coords.latitude,
              lng: position.coords.longitude,
            });
            setMarkerPosition({
              lat: position.coords.latitude,
              lng: position.coords.longitude,
            });
          },
          (error) => {
            console.error(error);
          }
        );
      });
    } else {
      console.error("Geolocation is not supported by this browser!");
    }
  }, []);

  const onMarkerDragEnd = (e) => {
    const newLat = e.latLng.lat();
    const newLng = e.latLng.lng();
    Geocode.fromLatLng(newLat, newLng).then(
      (response) => {
        setAddress(response.results[0].formatted_address);
        const addressArray = response.results[0].address_components;
        setArea(getArea(addressArray));
        setCity(getCity(addressArray));
        setState(getState(addressArray));
        setMapPosition({ lat: newLat, lng: newLng });
        setMarkerPosition({ lat: newLat, lng: newLng });
      },
      (error) => {
        console.log(error);
      }
    );
  };

  const getCity = (addressArray) => {
    let city = "";
    for (let i = 0; i < addressArray.length; i++) {
      if (
        addressArray[i].types[0] &&
        "administrative_area_level_2" === addressArray[i].types[0]
      ) {
        city = addressArray[i].long_name;
        return city;
      }
    }
  };

  const getArea = (addressArray) => {
    let area = "";
    for (let i = 0; i < addressArray.length; i++) {
      if (addressArray[i].types[0]) {
        for (let j = 0; j < addressArray[i].types.length; j++) {
          if (
            "sublocality_level_1" === addressArray[i].types[j] ||
            "locality" === addressArray[i].types[j]
          ) {
            area = addressArray[i].long_name;
            return area;
          }
        }
      }
    }
  };

  const getState = (addressArray) => {
    let state = "";
    for (let i = 0; i < addressArray.length; i++) {
      for (let i = 0; i < addressArray.length; i++) {
        if (
          addressArray[i].types[0] &&
          "administrative_area_level_1" === addressArray[i].types[0]
        ) {
          state = addressArray[i].long_name;
          return state;
        }
      }
    }
  };

  const onPlaceSelected = (place) => {
    const address = place.formatted_address;
    const addressArray = place.address_components;
    setAddress(address);
    setArea(getArea(addressArray));
    setCity(getCity(addressArray));
    setState(getState(addressArray));
    setMapPosition({
      lat: place.geometry.location.lat(),
      lng: place.geometry.location.lng(),
    });
    setMarkerPosition({
      lat: place.geometry.location.lat(),
      lng: place.geometry.location.lng(),
    });
  };
  const MyMapComponent = withScriptjs(
    withGoogleMap((props) => (
      <GoogleMap
        defaultZoom={zoom}
        defaultCenter={{ lat: mapPosition.lat, lng: mapPosition.lng }}
      >
        <Marker
          draggable={true}
          onDragEnd={onMarkerDragEnd}
          position={{ lat: markerPositon.lat, lng: markerPositon.lng }}
        >
          <InfoWindow>
            <div>{address}</div>
          </InfoWindow>
        </Marker>
        <AutoComplete
          style={{ width: "100%", height: "40px" }}
          onPlaceSelected={onPlaceSelected}
          types={["(regions"]}
        />
      </GoogleMap>
    ))
  );
  return (
    <div style={{ padding: "1rem", margin: "0 auto", maxWidth: 1000 }}>
      <h1>Google Map Basic</h1>
      <Descriptions bordered>
        <Descriptions.Item label="City">{city}</Descriptions.Item>
        <Descriptions.Item label="Area">{area}</Descriptions.Item>
        <Descriptions.Item label="State">{state}</Descriptions.Item>
        <Descriptions.Item label="Address">{address}</Descriptions.Item>
      </Descriptions>
      <MyMapComponent
        isMarkerShown
        googleMapURL="https://maps.googleapis.com/maps/api/js?key=AIzaS2YkwImI66tap6R_g4uqLOW07GM&v=3.exp&libraries=geometry,drawing,places"
        loadingElement={<div style={{ height: `100%` }} />}
        containerElement={<div style={{ height: `400px` }} />}
        mapElement={<div style={{ height: `100%` }} />}
      />
    </div>
  );
};

export default LandingPage;

 

전체코드는 다음과 같다. api key부분은 혹시 몰라 조금씩 지워놨다.

 

geolocation API - 현재 사용자의 위치를 파악.

 

geocode API -위도와 경도를 통해 그 위치의 정보들을 알 수 있다.

'React' 카테고리의 다른 글

presentational component와 container component  (0) 2020.08.19
antd Icon  (0) 2020.08.06
antd Carousel(auto), a href  (0) 2020.08.04
lazy component, Switch  (0) 2020.07.30
map method  (0) 2020.07.29

관련글 더보기

댓글 영역