我需要.route()
内部应用程序中的结果,而不是进入任何地图。我需要起点和终点之间的持续时间和距离,以便在我的应用程序中进行进一步计算。
到目前为止,我尝试了一个回调函数:
function getTravelTime(origin, destination, cb) {
const directionsService = new google.maps.DirectionsService();
directionsService.route(
{
origin: origin,
destination: destination,
travelMode: "DRIVING"
},
(result, status) => {
if (status === google.maps.DirectionsStatus.OK) {
cb(null, {
duration: moment.utc(moment.duration(result.routes[0].legs[0].duration.value, 'seconds').as('milliseconds')).format('HH:mm'),
distance: result.routes[0].legs[0].distance.value
});
} else {
cb('error');
console.log(result);
}
}
);
};
我试着这样读:
let tInfo = getTravelTime(origin, destination, function (err, dist) {
if (!err) {
let distanceBetweenLocations = dist.distance;
let durationBetweenLocations = dist.duration;
// Or with saving to a state
setTravelInformation(prevState => ({
distance: dist.distance,
duration: dist.duration
}));
}
});
有没有可能在不需要渲染地图的情况下计算距离和旅行时间?
到目前为止,我得到了这个,大大缩短了,因为我在同一个文件中为其他组件获得了更多的逻辑:
import {
withGoogleMap,
GoogleMap,
withScriptjs,
Marker,
DirectionsRenderer
} from "react-google-maps";
const getTravelTime = (origin, destination) => {
const directionsService = new google.maps.DirectionsService();
directionsService.route(
{
origin: origin,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING
},
(result, status) => {
console.log(result)
if (status === google.maps.DirectionsStatus.OK) {
setDirections(result);
} else {
setError(result);
}
}
);
}
我是否需要使用 HoC withScriptjs 并将我的组件包装起来?