我花了一些时间将谷歌地图与打字稿配置集成。所以我分享我的代码给你看看它会帮助你和其他人。
import React, {
Component
} from 'react'
import {
Map,
GoogleApiWrapper,
Marker,
InfoWindow
} from 'google-maps-react';
declare
var google: any;
interface IPageProps {
google ? : any;
center: ILatAndLng;
markersOptions: any[];
zoom: number;
containerStyle: any;
flightPositions ? : ILatAndLng[]
address ? : string;
centername ? : string
}
interface ILatAndLng {
lat: number;
lng: number;
}
export class MapComponent extends Component < IPageProps, any > {
constructor(props: any) {
super(props);
this.state = {
activeMarker: {},
selectedPlace: {},
showingInfoWindow: false
};
}
private onMarkerClick = (props: any, marker: any) =>
this.setState({
activeMarker: marker,
selectedPlace: props,
showingInfoWindow: true
});
private onInfoWindowClose = () =>
this.setState({
activeMarker: null,
showingInfoWindow: false
});
private onMapClicked = () => {
if (this.state.showingInfoWindow) {
this.setState({
activeMarker: null,
showingInfoWindow: false
});
}
};
public render() {
const {
markersOptions,
center,
zoom,
containerStyle,
flightPositions,
address
} = this.props
return ( <
Map google = {
this.props.google
}
onClick = {
this.onMapClicked
}
initialCenter = {
center
}
center = {
{
lat: center.lat,
lng: center.lng
}
}
/** @ts-ignore */
flightPlanCoordinates = {
flightPositions
}
zoom = {
zoom
}
containerStyle = {
containerStyle
} >
{
(Array.isArray(markersOptions) && markersOptions.length > 0) ? markersOptions.map((marker: any, markerIndex: number) => {
return ( <
Marker key = {
'marker ' + markerIndex
}
/** @ts-ignore */
label = {
markerIndex.toString()
}
name = {
markerIndex.toString()
}
onClick = {
this.onMarkerClick
}
position = {
{
lat: +marker.latitude,
lng: +marker.longitude
}
}
/>
)
}) : (center.lat !== null) && < Marker
/** @ts-ignore */
name = {
address
}
label = {
'H'
}
onClick = {
this.onMarkerClick
}
position = {
{
lat: center.lat,
lng: center.lng
}
}
/>} <
InfoWindow
marker = {
this.state.activeMarker
}
/** @ts-ignore */
onClose = {
this.onInfoWindowClose
}
visible = {
this.state.showingInfoWindow
} >
<
div >
<
h4 > {
/** @ts-ignore */
this.state.selectedPlace.name
} < /h4> <
/div> <
/InfoWindow> <
/Map>
);
}
}
const Container = GoogleApiWrapper({
apiKey: process.env.REACT_APP_GOOGLE_MAP_KEY,
version: "3.38",
region: 'US'
})(MapComponent as any) as any;
export default Container;