我想添加一个应用程序地图到我的应用程序。在这个我需要添加一个按钮,将控制台日志("嗨,我在这里")当点击。
这里使用的包是"react-google-map ">
const handleOnLoad = GoogleMap => {
const controlButtonDiv = document.createElement('div');
ReactDOM.render(<CustomControl onClick={() => console.log('Hi I'm Here')} />, controlButtonDiv);
GoogleMap.controls[window.google.maps.ControlPosition.TOP_RIGHT].push(controlButtonDiv);
};
<GoogleMap
defaultZoom={16}
defaultCenter={{ lat: this.props.latVal, lng: this.props.longVal}}
onTilesLoaded={GoogleMap => handleOnLoad(GoogleMap)}
>
<Marker
position={this.state.progress[this.state.progress.length - 1]}
icon={{
url: 'https://images.vexels.com/media/users/3/154573/isolated/preview/bd08e000a449288c914d851cb9dae110-hatchback-car-top-view-silhouette-by-vexels.png',
scaledSize: new window.google.maps.Size(50, 50),
anchor: { x: 10, y: 10 }
}}
/>
<Polyline
path={this.state.progress}
options={{ strokeColor: "#FF0000" }}
/>
<Circle
defaultCenter={{lat: this.props.latVal, lng: this.props.longVal}}
radius={parseInt(this.props.geofence)}
options={{strokeColor: "#ff0000"}}
/>
</GoogleMap>
如果你正在使用React>= 16.8 (hooks),我建议你更新到@react-google-maps/api。然后你可以用几行代码创建一个可重用的MapControl:
interface MapControlProps {
position: keyof typeof google.maps.ControlPosition;
}
const MapControl = (props: React.PropsWithChildren<MapControlProps>) => {
const map = useGoogleMap();
const ref = useRef();
useEffect(() => {
if (map && ref) {
map.controls[window.google.maps.ControlPosition[props.position]].push(
ref.current
);
}
}, [map, ref]);
return <div ref={ref}>{props.children}</div>;
};
然后你可以在你的<GoogleMap>
里面放置一个<MapControl>
使用任何你喜欢的内容
<GoogleMap
defaultZoom={16}
defaultCenter={{ lat: this.props.latVal, lng: this.props.longVal}}
onTilesLoaded={GoogleMap => handleOnLoad(GoogleMap)}
>
<MapControl position="LEFT_BOTTOM">
<button
style={{ backgroundColor: "red" }}
onClick={() => console.log('Hi I'm Here')}
>
CLICK ME
</button>
<input placeholder="type some stuff" />
</MapControl>
</GoogleMap>