当使用react-google-maps库时。我已经找到了DirectionsRenderer,但我只看到选项中包含了一个起点和一个目的地。
是否可以包含多个路点?
发布于 2021-10-07 01:13:15
可以,您可以包含多个路点。正如您在DirectionsRenderer sample中看到的,它使用const DirectionsService = new google.maps.DirectionsService();。您可以参考DirectionsService doc上的示例,了解如何在请求中包含路点。
以下是示例代码片段:
import React, { Component } from 'react';
import {
withGoogleMap,
GoogleMap,
DirectionsRenderer,
} from 'react-google-maps';
class Map extends Component {
state = {
directions: null,
};
componentDidMount() {
const directionsService = new google.maps.DirectionsService();
const origin = { lat: 40.756795, lng: -73.954298 };
const destination = { lat: 41.756795, lng: -78.954298 };
const waypt = [
{
location: { lat: 40.278022, lng: -76.899615 },
stopover: true,
},
{
location: { lat: 40.750216, lng: -78.922049 },
stopover: true,
},
];
directionsService.route(
{
origin: origin,
destination: destination,
waypoints: waypt,
travelMode: google.maps.TravelMode.DRIVING,
},
(result, status) => {
if (status === google.maps.DirectionsStatus.OK) {
this.setState({
directions: result,
});
} else {
console.error(`error fetching directions ${result}`);
}
}
);
}
render() {
const GoogleMapExample = withGoogleMap((props) => (
<GoogleMap
defaultCenter={{ lat: 40.756795, lng: -73.954298 }}
defaultZoom={13}
>
{this.state.directions && (
<DirectionsRenderer directions={this.state.directions} />
)}
</GoogleMap>
));
return (
<div>
<GoogleMapExample
containerElement={<div style={{ height: `500px`, width: '500px' }} />}
mapElement={<div style={{ height: `100%` }} />}
/>
</div>
);
}
}
export default Map;https://stackoverflow.com/questions/46696324
复制相似问题