programing

Google-map-react에서 Google 지도에 마커 추가

codeshow 2023. 3. 8. 21:40
반응형

Google-map-react에서 Google 지도에 마커 추가

NPM 패키지를 사용하여 Google 지도와 여러 마커를 만들고 있습니다.

질문:기본 Google 지도 마커를 지도에 추가하려면 어떻게 해야 합니까?

이번 Github 문제부터는 onGoogleApiLoaded 함수를 사용하여 내부 Google Maps API에 접속해야 할 것 같습니다.

Google Maps JS API 문서의 예를 참조하면 다음 코드를 사용하여 마커를 렌더링할 수 있지만 참조를 정의하는 방법은 무엇입니까?map?

var marker = new google.maps.Marker({
    position: myLatLng,
    map: map,
    title: 'Hello World!'
});

현재 코드:

renderMarkers() {
    ...
}

render() {
    return (
        <div style={{'width':800,'height':800}}>
            <GoogleMap
                bootstrapURLKeys={{key: settings.googleMapApiKey}}
                defaultZoom={13}
                defaultCenter={{ 
                    lat: this.props.user.profile.location.coordinates[1], 
                    lng: this.props.user.profile.location.coordinates[0]
                }}
                onGoogleApiLoaded={({map, maps}) => this.renderMarkers()}
                yesIWantToUseGoogleMapApiInternals
            >
            </GoogleMap>
        </div>
    );
}

편집:
이 답변이 투고된 이후, (아마도 API)의 docs는GoogleMapReact요소가 어린이를 지원하도록 변경되었습니다.의 모든 자녀lat그리고.lng@Jobsamuel의 답변에서도 알 수 있듯이 지도상의 해당 위치에 렌더링됩니다.

onGoogleApiLoaded콜백은 선언 스타일보다 열등하며 맵에 변경이 가해져도 재실행되지 않기 때문에 이 목적을 위해 사용하지 마십시오.


원래 답변(구식):

이것은 Readme의 설명에서 완전히 명확하지 않을 수 있지만,maps인수는 실제로는 맵 API 오브젝트입니다.map물론 현재 Google Map 인스턴스입니다).따라서 두 가지 방법을 모두 사용해야 합니다.

onGoogleApiLoaded={({map, maps}) => this.renderMarkers(map, maps)}

사용:

renderMarkers(map, maps) {
  let marker = new maps.Marker({
    position: myLatLng,
    map,
    title: 'Hello World!'
  });
}

지도에 마커를 추가하는 것은 쉽지 않습니다. 주로 문서가 혼란스럽기 때문입니다만, 여기 매우 간단한 예가 있습니다.

const Map = props => {
  return (
    <GoogleMapReact
     bootstrapURLKeys={{ props.key }}
     defaultCenter={{lat: props.lat, lng: props.lng}}
     defaultZoom={props.zoom}>

       {/* This is the missing part in docs:
         *
         * Basically, you only need to add a Child Component that
         * takes 'lat' and 'lng' Props. And that Component should
         * returns a text, image, super-awesome-pin (aka, your marker).
         *
         */}
       <Marker lat={props.lat} lng={props.lng}} />
    </GoogleMapReact>
  )
}

const Marker = props => {
  return <div className="SuperAwesomePin"></div>
}
import React from 'react';
import GoogleMapReact from 'google-map-react';

const GoogleMaps = ({ latitude, longitude }) => {
 const renderMarkers = (map, maps) => {
  let marker = new maps.Marker({
  position: { lat: latitude, lng: longitude },
  map,
  title: 'Hello World!'
  });
  return marker;
 };

 return (
   <div style={{ height: '50vh', width: '100%' }}>
    <GoogleMapReact
      bootstrapURLKeys={{ key: 'YOUR KEY' }}
      defaultCenter={{ lat: latitude, lng: longitude }}
      defaultZoom={16}
      yesIWantToUseGoogleMapApiInternals
      onGoogleApiLoaded={({ map, maps }) => renderMarkers(map, maps)}
    >
    </GoogleMapReact>
   </div>
 );
};

export default GoogleMaps;

마스터의 답변을 바탕으로 합니다.오전.

리액트 훅을 사용하면 다음과 같은 효과를 얻을 수 있습니다.

import React, { useMemo, useEffect } from 'react';

const createControlledPromise = () => {
  let resolver;
  let rejector;
  const promise = new Promise((resolve, reject) => {
    resolver = resolve;
    rejector = reject;
  });
  return { promise, resolver, rejector };
};

const useMarker = ({ lat, lng }) => {
  const { 
    promise: apiPromise, 
    resolver: handleGoogleApiLoaded 
  } = useMemo(
    createControlledPromise,
    []
  ).current;

  useEffect(
    () => {
      let marker;
      apiPromise.then(api => {
        const { map, maps } = api;
        marker = new maps.Marker({ position: { lat, lng }, map });
      });
      return () => {
        if (marker) {
          marker.setMap(null);
        }
      };
    },
    [lat, lon],
  );
  return { handleGoogleApiLoaded };
};

const Location = ({
  location: { locationName, lat, lng }
}) => {
  const { handleGoogleApiLoaded } = useMarker({ lat, lng });
  return (
    <section>
      <h1>{locationName}</h1>
      <p>
        <GoogleMapReact
          bootstrapURLKeys={{ key: __GOOGLE_MAP_API_KEY__ }}
          center={{ lat, lng }}
          defaultZoom={11}
          onGoogleApiLoaded={handleGoogleApiLoaded}
        />
      </p>
    </section>
  );
};

언급URL : https://stackoverflow.com/questions/41405343/adding-marker-to-google-maps-in-google-map-react

반응형