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
'programing' 카테고리의 다른 글
컨트롤러가 필요한 테스트 지침 (0) | 2023.03.13 |
---|---|
콘텐츠 유형 'application/x-www-form-urlencoded;charset=UTF-8'은 @RequestBody MultiValueMap에서 지원되지 않습니다. (0) | 2023.03.08 |
Spring Boot/Spring Security에서 사용자가 자신의 데이터에만 접근할 수 있도록 하는 방법 (0) | 2023.03.08 |
사용자 지정 분류법이 Post Gutenberg 편집기에 표시되지 않음 (0) | 2023.03.08 |
JsonConvert에서 null/empt 값을 처리하는 방법.디시리얼라이즈 오브젝트 (0) | 2023.03.08 |