Я пытаюсь рассчитать маршрут между двумя точками, используя направления карт Google. Когда я попробовал следующий код, я получил сообщение об ошибке:
Доступ к выборке в «https://maps.googleapis.com/maps/api/directions/json?destination=31.922007%2C34.768531&mode=driving&origin=32.087001%2C34.8226326&key=MY_KEY» из источника «http: // локальный: 3000» был заблокирован политикой CORS: на запрошенном ресурсе отсутствует заголовок «Access-Control-Allow-Origin». Если непрозрачный ответ соответствует вашим потребностям, установите для режима запроса значение «no-cors», чтобы получить ресурс с отключенным CORS.
Я видел здесь: Запрос CORS не работает в API маршрутов Google, что я не могу использовать API таким образом, но могу использовать службу направления https://developers.google.com/maps/documentation/javascript/directions
import { createClient } from '@google/maps';
import { GOOGLE_GEOCODE_API_KEY } from '../config/keys';
let googleMapsClient;
function initialize() {
googleMapsClient = createClient({key: GOOGLE_GEOCODE_API_KEY});
}
function getGoogleMapsClient() {
if (!googleMapsClient) {
initialize();
}
return googleMapsClient;
}
function calcRoute(origin, destination) {
return getGoogleMapsClient().directions({
origin: origin,
destination: destination,
mode: 'driving',
});
}
Как я понимаю из документов службы маршрутов, я должен предоставить карту в моем приложении, чтобы произвести расчет маршрута, но я не хочу этого делать. Кроме того, документы посвящены JS, и я работаю с react. Как я могу произвести расчет в React без отображения карты?





Экземпляр карты не является обязательным для использования Служба маршрутов Google Maps, также поддерживается передача элемента <div> для визуализации информации о маршруте из документации:
A
DirectionsRenderernot only handles display of the polyline and any associated markers, but also can handle the textual display of directions as a series of steps. To do so, simply call setPanel() on yourDirectionsRenderer, passing it the in which to display this information.
Вот пример:
class RouteInfo extends Component {
constructor(props) {
super(props);
this.directionsPanelRef = React.createRef();
this.directionsDisplay = new google.maps.DirectionsRenderer();
this.directionsService = new google.maps.DirectionsService();
}
componentDidMount() {
this.directionsDisplay.setPanel(this.directionsPanelRef.current);
this.displayRoute();
}
displayRoute() {
this.request = {
origin: "chicago, il",
destination: "st louis, mo",
travelMode: google.maps.TravelMode.DRIVING
};
this.directionsService.route(this.request, (response, status) => {
if (status === google.maps.DirectionsStatus.OK) {
this.directionsDisplay.setDirections(response);
} else {
console.info("Directions request failed due to " + status);
}
});
}
render() {
return (
<div>
<div ref = {this.directionsPanelRef} />
</div>
);
}
}
Вот такой демонстрация