您可以执行类似这样的操作(示例代码和代码片段如下),其中您将在加载 API 时传递地图对象,然后使用 apiIsLoaded 函数调用路线服务。
import React, { Component } from "react";
import GoogleMapReact from "google-map-react";
import "./style.css";
class GoogleMaps extends Component {
constructor(props) {
super(props);
this.state = {
currentLocation: { lat: 40.756795, lng: -73.954298 }
};
}
render() {
const apiIsLoaded = (map, maps) => {
const directionsService = new google.maps.DirectionsService();
const directionsRenderer = new google.maps.DirectionsRenderer();
directionsRenderer.setMap(map);
const origin = { lat: 40.756795, lng: -73.954298 };
const destination = { lat: 41.756795, lng: -78.954298 };
directionsService.route(
{
origin: origin,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING
},
(result, status) => {
if (status === google.maps.DirectionsStatus.OK) {
directionsRenderer.setDirections(result);
} else {
console.error(`error fetching directions ${result}`);
}
}
);
};
return (
<div>
<div style={{ height: "400px", width: "100%" }}>
<GoogleMapReact
bootstrapURLKeys={{
key: "YOUR_API_KEY"
}}
defaultCenter={{ lat: 40.756795, lng: -73.954298 }}
defaultZoom={10}
center={this.state.currentLocation}
yesIWantToUseGoogleMapApiInternals
onGoogleApiLoaded={({ map, maps }) => apiIsLoaded(map, maps)}
/>
</div>
</div>
);
}
}
export default GoogleMaps;