조경 어플 만들기

moon.kick·2025년 1월 3일

LAB

목록 보기
5/6
post-thumbnail
src/
  ├─ App.js
  ├─ components/
  │    ├─ GreenCalculator.js   (부모 컴포넌트)
  │    ├─ CountryInput.js      (자식 컴포넌트 #1: 국가 입력)
  │    ├─ ResultView.js        (자식 컴포넌트 #2: 결과 + 지도)
  │    └─ GoogleMap.js         (지도 표시 컴포넌트)
  └─ index.js 

전체 구조 요약

GreenCalculator (부모 컴포넌트)

selectedCountry라는 상태(state)를 갖고 있음
자식 #1: CountryInput 에서 국가명을 입력받으면, handleCountrySubmit 함수를 통해 selectedCountry를 업데이트
자식 #2: ResultView 에 selectedCountry를 넘겨, 해당 국가 정보와 지도를 화면에 표시

CountryInput (자식 1)

간단한 "< form >" 요소로 국가명을 입력받음

폼이 제출되면(handleSubmit), 입력된 국가명을 부모로 전달

ResultView (자식 2)

하드코딩된 countriesData에서 국가 정보를 찾음
찾은 정보(면적, 녹지 면적)로 녹지 비율을 계산
지도 표시를 위해 GoogleMap 컴포넌트에 현재 국가명을 내려 줌

GoogleMap

countryName을 받아서 geocoding (Google Maps Geocoding)으로 해당 국가의 위치(위도·경도)를 찾음
찾은 위치를 지도 중앙으로 설정하고 마커를 표시
Google Maps JavaScript API를 동적으로 "< script >" 로드하여 사용

전체 구조 요약

1 GreenCalculator (부모 컴포넌트)

selectedCountry라는 상태(state)를 갖고 있음
자식 #1: CountryInput 에서 국가명을 입력받으면, handleCountrySubmit 함수를 통해 selectedCountry를 업데이트
자식 #2: ResultView 에 selectedCountry를 넘겨, 해당 국가 정보와 지도를 화면에 표시

function GreenCalculator() {
  const [selectedCountry, setSelectedCountry] = useState('');

  const handleCountrySubmit = (country) => {
    setSelectedCountry(country);
  };

  return (
    <div style={styles.calculatorContainer}>
      <h2>국가별 녹지 면적 계산기</h2>
      <CountryInput onCountrySubmit={handleCountrySubmit} />
      <hr />
      <ResultView countryName={selectedCountry} />
    </div>
  );
}

2CountryInput (자식 1)

간단한 < form > 요소로 국가명을 입력받음
폼이 제출되면(handleSubmit), 입력된 국가명을 부모로 전달

function CountryInput({ onCountrySubmit }) {
  const [inputValue, setInputValue] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    onCountrySubmit(inputValue.trim());
  };

  return (
    <form onSubmit={handleSubmit} style={styles.form}>
      <label style={styles.label}>국가 입력:</label>
      <input
        type="text"
        placeholder="예: South Korea"
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
        style={styles.input}
      />
      <button type="submit" style={styles.button}>계산</button>
    </form>
  );
}

3ResultView (자식 2)

하드코딩된 countriesData에서 국가 정보를 찾음
찾은 정보(면적, 녹지 면적)로 녹지 비율을 계산
지도 표시를 위해 GoogleMap 컴포넌트에 현재 국가명을 내려 줌

const countriesData = {
  'South Korea': {
    area: 100210,
    greenArea: 62710,
  },
  // ...
};


  function ResultView({ countryName }) {
  const data = countriesData[countryName];

  if (!countryName) {
    return <p>국가를 입력해 주세요.</p>;
  }

  if (!data) {
    return <p style={{ color: 'red' }}>해당 국가 데이터가 없습니다.</p>;
  }

  const greenRatio = ((data.greenArea / data.area) * 100).toFixed(2);

  return (
    <div>
      <h3>결과</h3>
      <p>국가: {countryName}</p>
      <p>전체 면적: {data.area} km²</p>
      <p>녹지 면적: {data.greenArea} km²</p>
      <p>녹지 비율: {greenRatio}%</p>

      <GoogleMap countryName={countryName} />
    </div>
  );
}

4GoogleMap

countryName을 받아서 geocoding (Google Maps Geocoding)으로 해당 국가의 위치(위도·경도)를 찾음
찾은 위치를 지도 중앙으로 설정하고 마커를 표시
Google Maps JavaScript API를 동적으로 < scrip t> 로드하여 사용

useEffect(() => {
  if (!countryName) return;

  const existingScript = document.getElementById('googleMaps');
  if (!existingScript) {
    const script = document.createElement('script');
    script.src = `https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places`;
    script.id = 'googleMaps';
    document.body.appendChild(script);
    script.onload = () => initMap(countryName);
  } else {
    initMap(countryName);
  }

  function initMap(country) {
    const geocoder = new window.google.maps.Geocoder();
    geocoder.geocode({ address: country }, (results, status) => {
      if (status === 'OK' && results[0]) {
        const location = results[0].geometry.location;
        const mapOptions = {
          zoom: 5,
          center: location,
        };
        const mapDiv = document.getElementById('map');
        const newMap = new window.google.maps.Map(mapDiv, mapOptions);

        new window.google.maps.Marker({
          position: location,
          map: newMap,
          title: country,
        });

        setMap(newMap);
      } else {
        console.error('Geocode was not successful for the following reason:', status);
      }
    });
  }
}, [countryName]);

정리

사용자가 CountryInput에서 국가 이름을 입력하면 → GreenCalculator가 이를 selectedCountry로 저장 → ResultView는 그 selectedCountry에 맞는 데이터(면적, 녹지) 및 녹지 비율을 계산해서 화면 표시 → GoogleMap은 selectedCountry의 지리 정보를 불러와 지도를 중앙으로 설정하고 마커를 찍어 줌.

이게 가능한건지..

profile
@mgkick

0개의 댓글