Маршрут — это проходимый путь между начальной точкой (отправной точкой) и конечной точкой (пунктом назначения). Вы можете выбрать маршрут для различных видов транспорта, таких как пешая прогулка, езда на велосипеде или различные типы транспортных средств. Вы также можете запросить подробную информацию о маршруте, такую как расстояние, расчетное время в пути, ожидаемые сборы и пошаговые инструкции по прохождению маршрута.
См. полный пример исходного кода.
Приведенный ниже пример кода демонстрирует, как получить маршрут для автомобильного движения между двумя точками.
Машинопись
// Initialize and add the map. let map; let mapPolylines: google.maps.Polyline[] = []; const center = { lat: 37.447646, lng: -122.113878 }; // Palo Alto, CA // Initialize and add the map. async function initMap(): Promise<void> { // Request the needed libraries. const [{ Map }, { Place }, { Route }] = await Promise.all([ google.maps.importLibrary('maps') as Promise<google.maps.MapsLibrary>, google.maps.importLibrary( 'places' ) as Promise<google.maps.PlacesLibrary>, //@ts-ignore google.maps.importLibrary('routes') as Promise<google.maps.Routes>, ]); map = new Map(document.getElementById('map') as HTMLElement, { zoom: 12, center: center, mapTypeControl: false, mapId: 'DEMO_MAP_ID', }); // Use address strings in a directions request. const requestWithAddressStrings = { origin: '1600 Amphitheatre Parkway, Mountain View, CA', destination: '345 Spear Street, San Francisco, CA', fields: ['path'], }; // Use Place IDs in a directions request. const originPlaceInstance = new Place({ id: 'ChIJiQHsW0m3j4ARm69rRkrUF3w', // Mountain View, CA }); const destinationPlaceInstance = new Place({ id: 'ChIJIQBpAG2ahYAR_6128GcTUEo', // San Francisco, CA }); const requestWithPlaceIds = { origin: originPlaceInstance, destination: destinationPlaceInstance, fields: ['path'], // Request fields needed to draw polylines. }; // Use lat/lng in a directions request. // Mountain View, CA const originLatLng = { lat: 37.422, lng: -122.084058 }; // San Francisco, CA const destinationLatLng = { lat: 37.774929, lng: -122.419415 }; // Define a computeRoutes request. const requestWithLatLngs = { origin: originLatLng, destination: destinationLatLng, fields: ['path'], }; // Use Plus Codes in a directions request. const requestWithPlusCodes = { origin: '849VCWC8+R9', // Mountain View, CA destination: 'CRHJ+C3 Stanford, CA 94305, USA', // Stanford, CA fields: ['path'], }; // Define a routes request. const request = { origin: 'Mountain View, CA', destination: 'San Francisco, CA', travelMode: 'DRIVING', fields: ['path'], // Request fields needed to draw polylines. }; // Call computeRoutes to get the directions. const { routes, fallbackInfo, geocodingResults } = await Route.computeRoutes(request); // Use createPolylines to create polylines for the route. mapPolylines = routes[0].createPolylines(); // Add polylines to the map. mapPolylines.forEach((polyline) => polyline.setMap(map)); // Create markers to start and end points. const markers = await routes[0].createWaypointAdvancedMarkers(); // Add markers to the map markers.forEach((marker) => marker.setMap(map)); // Display the raw JSON for the result in the console. console.log(`Response:\n ${JSON.stringify(routes, null, 2)}`); // Fit the map to the path. fitMapToPath(routes[0].path!); } // Helper function to fit the map to the path. async function fitMapToPath(path) { const { LatLngBounds } = (await google.maps.importLibrary( 'core' )) as google.maps.CoreLibrary; const bounds = new LatLngBounds(); path.forEach((point) => { bounds.extend(point); }); map.fitBounds(bounds); } initMap();
JavaScript
// Initialize and add the map. let map; let mapPolylines = []; const center = { lat: 37.447646, lng: -122.113878 }; // Palo Alto, CA // Initialize and add the map. async function initMap() { // Request the needed libraries. const [{ Map }, { Place }, { Route }] = await Promise.all([ google.maps.importLibrary('maps'), google.maps.importLibrary('places'), //@ts-ignore google.maps.importLibrary('routes'), ]); map = new Map(document.getElementById('map'), { zoom: 12, center: center, mapTypeControl: false, mapId: 'DEMO_MAP_ID', }); // Use address strings in a directions request. const requestWithAddressStrings = { origin: '1600 Amphitheatre Parkway, Mountain View, CA', destination: '345 Spear Street, San Francisco, CA', fields: ['path'], }; // Use Place IDs in a directions request. const originPlaceInstance = new Place({ id: 'ChIJiQHsW0m3j4ARm69rRkrUF3w', // Mountain View, CA }); const destinationPlaceInstance = new Place({ id: 'ChIJIQBpAG2ahYAR_6128GcTUEo', // San Francisco, CA }); const requestWithPlaceIds = { origin: originPlaceInstance, destination: destinationPlaceInstance, fields: ['path'], // Request fields needed to draw polylines. }; // Use lat/lng in a directions request. // Mountain View, CA const originLatLng = { lat: 37.422, lng: -122.084058 }; // San Francisco, CA const destinationLatLng = { lat: 37.774929, lng: -122.419415 }; // Define a computeRoutes request. const requestWithLatLngs = { origin: originLatLng, destination: destinationLatLng, fields: ['path'], }; // Use Plus Codes in a directions request. const requestWithPlusCodes = { origin: '849VCWC8+R9', // Mountain View, CA destination: 'CRHJ+C3 Stanford, CA 94305, USA', // Stanford, CA fields: ['path'], }; // Define a routes request. const request = { origin: 'Mountain View, CA', destination: 'San Francisco, CA', travelMode: 'DRIVING', fields: ['path'], // Request fields needed to draw polylines. }; // Call computeRoutes to get the directions. const { routes, fallbackInfo, geocodingResults } = await Route.computeRoutes(request); // Use createPolylines to create polylines for the route. mapPolylines = routes[0].createPolylines(); // Add polylines to the map. mapPolylines.forEach((polyline) => polyline.setMap(map)); // Create markers to start and end points. const markers = await routes[0].createWaypointAdvancedMarkers(); // Add markers to the map markers.forEach((marker) => marker.setMap(map)); // Display the raw JSON for the result in the console. console.log(`Response:\n ${JSON.stringify(routes, null, 2)}`); // Fit the map to the path. fitMapToPath(routes[0].path); } // Helper function to fit the map to the path. async function fitMapToPath(path) { const { LatLngBounds } = (await google.maps.importLibrary('core')); const bounds = new LatLngBounds(); path.forEach((point) => { bounds.extend(point); }); map.fitBounds(bounds); } initMap();
CSS
/* * Always set the map height explicitly to define the size of the div element * that contains the map. */ #map { height: 100%; } /* * Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; padding: 0; }
HTML
<html>
<head>
<title>Get directions</title>
<link rel="stylesheet" type="text/css" href="./style.css" />
<script type="module" src="./index.js"></script>
</head>
<body>
<div id="map"></div>
<!-- prettier-ignore -->
<script>(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})
({key: "AIzaSyA6myHzS10YXdcazAFalmXvDkrYCp5cLc8", v: "beta"});</script>
</body>
</html>Попробуйте образец
Для запроса маршрута между двумя точками вызовите метод computeRoutes() . В следующем примере показано, как определить запрос, а затем вызвать computeRoutes() для получения маршрута.
// Import the Routes library. const { Route } = await google.maps.importLibrary('routes'); // Define a computeRoutes request. const request = { origin: 'Mountain View, CA', destination: 'San Francisco, CA', }; // Call the computeRoutes() method to get routes. const {routes} = await Route.computeRoutes(request);
Выберите поля для возврата
При запросе маршрута необходимо использовать маску поля, чтобы указать, какую информацию должен вернуть ответ. В маске поля можно указать имена свойств класса Route .
Использование маски поля также гарантирует, что вы не будете запрашивать ненужные данные, что, в свою очередь, помогает уменьшить задержку ответа и избежать возврата информации, которая вашей системе не нужна.
Укажите список необходимых полей, задав свойство ComputeRoutesRequest.fields , как показано в следующем фрагменте кода:
Машинопись
// Define a routes request. const request = { origin: 'Mountain View, CA', destination: 'San Francisco, CA', travelMode: 'DRIVING', fields: ['path'], // Request fields needed to draw polylines. };
JavaScript
// Define a routes request. const request = { origin: 'Mountain View, CA', destination: 'San Francisco, CA', travelMode: 'DRIVING', fields: ['path'], // Request fields needed to draw polylines. };
Укажите места для маршрута
Для расчета маршрута необходимо указать как минимум начальную и конечную точки маршрута, а также маску поля. Можно также указать промежуточные точки вдоль маршрута и использовать их для других целей, например, для добавления остановок или точек сквозного проезда.
В объекте ComputeRoutesRequest можно указать местоположение одним из следующих способов:
- Место (предпочтительное)
- Координаты широты/долготы
- Адресная строка ("Чикаго, Иллинойс" или "Дарвин, Северная территория, Австралия")
- Плюс-код
В запросе можно указать местоположения для всех путевых точек одинаковым образом или же смешать их. Например, для начальной путевой точки можно использовать координаты широты/долготы, а для конечной — объект Place.
Для повышения эффективности и точности используйте объекты Place вместо координат широты/долготы или строковых адресов. Идентификаторы Place являются уникальными и обеспечивают преимущества геокодирования для маршрутизации, например, для точек доступа и переменных трафика. Они помогают избежать следующих ситуаций, которые могут возникнуть при использовании других способов указания местоположения:
- Использование координат широты/долготы может привести к тому, что местоположение будет привязано к ближайшей к этим координатам дороге, которая может не являться подъездной дорогой к объекту или даже дорогой, которая быстро и безопасно ведет к месту назначения.
- Перед расчетом маршрута адресные строки должны быть предварительно геокодированы с помощью API маршрутов для преобразования их в координаты широты и долготы. Это преобразование может повлиять на производительность.
Укажите местоположение в виде объекта Place (предпочтительный вариант).
Чтобы указать местоположение с помощью объекта Place, создайте новый экземпляр Place . В следующем фрагменте кода показано создание новых экземпляров Place для origin и destination , а затем их использование в ComputeRoutesRequest :
Машинопись
// Use Place IDs in a directions request. const originPlaceInstance = new Place({ id: 'ChIJiQHsW0m3j4ARm69rRkrUF3w', // Mountain View, CA }); const destinationPlaceInstance = new Place({ id: 'ChIJIQBpAG2ahYAR_6128GcTUEo', // San Francisco, CA }); const requestWithPlaceIds = { origin: originPlaceInstance, destination: destinationPlaceInstance, fields: ['path'], // Request fields needed to draw polylines. };
JavaScript
// Use Place IDs in a directions request. const originPlaceInstance = new Place({ id: 'ChIJiQHsW0m3j4ARm69rRkrUF3w', // Mountain View, CA }); const destinationPlaceInstance = new Place({ id: 'ChIJIQBpAG2ahYAR_6128GcTUEo', // San Francisco, CA }); const requestWithPlaceIds = { origin: originPlaceInstance, destination: destinationPlaceInstance, fields: ['path'], // Request fields needed to draw polylines. };
Координаты широты/долготы
Чтобы указать местоположение в координатах широты/долготы, создайте новый экземпляр google.maps.LatLngLiteral , google.maps.LatLngAltitude или google.maps.LatLngAltitudeLiteral . В следующем фрагменте кода показано создание новых экземпляров google.maps.LatLngLiteral для origin и destination , а затем их использование в computeRoutesRequest :
Машинопись
// Use lat/lng in a directions request. // Mountain View, CA const originLatLng = { lat: 37.422, lng: -122.084058 }; // San Francisco, CA const destinationLatLng = { lat: 37.774929, lng: -122.419415 }; // Define a computeRoutes request. const requestWithLatLngs = { origin: originLatLng, destination: destinationLatLng, fields: ['path'], };
JavaScript
// Use lat/lng in a directions request. // Mountain View, CA const originLatLng = { lat: 37.422, lng: -122.084058 }; // San Francisco, CA const destinationLatLng = { lat: 37.774929, lng: -122.419415 }; // Define a computeRoutes request. const requestWithLatLngs = { origin: originLatLng, destination: destinationLatLng, fields: ['path'], };
Адресная строка
Адресные строки — это буквальные адреса, представленные строкой (например, "1600 Amphitheatre Parkway, Mountain View, CA"). Геокодирование — это процесс преобразования адресной строки в координаты широты и долготы (например, широта 37.423021 и долгота -122.083739).
Когда вы передаете строковый адрес в качестве местоположения путевой точки, библиотека Routes внутренне выполняет геокодирование строки, преобразуя ее в координаты широты и долготы.
Следующий фрагмент кода демонстрирует создание объекта ComputeRoutesRequest с адресной строкой для origin и destination :
Машинопись
// Use address strings in a directions request. const requestWithAddressStrings = { origin: '1600 Amphitheatre Parkway, Mountain View, CA', destination: '345 Spear Street, San Francisco, CA', fields: ['path'], };
JavaScript
// Use address strings in a directions request. const requestWithAddressStrings = { origin: '1600 Amphitheatre Parkway, Mountain View, CA', destination: '345 Spear Street, San Francisco, CA', fields: ['path'], };
Укажите регион для адреса.
Если в качестве местоположения путевой точки передать неполную строку адреса, API может использовать неверные геокодированные координаты широты/долготы. Например, вы отправляете запрос, указав «Толедо» в качестве начальной точки и «Мадрид» в качестве конечной точки маршрута:
// Define a request with an incomplete address string. const request = { origin: 'Toledo', destination: 'Madrid', };
В этом примере "Толедо" интерпретируется как город в штате Огайо, США, а не в Испании. Следовательно, запрос возвращает пустой массив, что означает отсутствие маршрутов.
Вы можете настроить API для возврата результатов, ориентированных на определенный регион, добавив параметр regionCode. Этот параметр задает код региона в виде двухсимвольного значения ccTLD («домен верхнего уровня») . Большинство кодов ccTLD идентичны кодам ISO 3166-1, за некоторыми заметными исключениями. Например, ccTLD Соединенного Королевства — «uk» (.co.uk), а его код ISO 3166-1 — «gb» (технически это означает «Соединенное Королевство Великобритании и Северной Ирландии»).
Запрос маршрута из "Толедо" в "Мадрид", содержащий параметр regionCode, возвращает корректные результаты, поскольку "Толедо" интерпретируется как город в Испании:
const request = { origin: 'Toledo', destination: 'Madrid', region: 'es', // Specify the region code for Spain. };
Плюс-код
У многих людей нет точного адреса, что может затруднить получение доставок. Или же люди, у которых есть адрес, могут предпочитать получать посылки в более конкретных местах, например, у заднего входа или на погрузочной площадке.
Плюс-коды — это как уличные адреса для людей или мест, у которых нет фактического адреса. Вместо адресов с названиями улиц и номерами домов, плюс-коды основаны на координатах широты/долготы и отображаются в виде цифр и букв.
Компания Google разработала Plus Codes, чтобы сделать использование адресов доступным для всех и для всего. Plus Code — это закодированный идентификатор местоположения, полученный из координат широты и долготы, который обозначает область размером 1/8000 градуса на 1/8000 градуса (примерно 14 м x 14 м на экваторе) или меньше. Plus Codes можно использовать вместо уличных адресов в местах, где их нет, где здания не нумеруются, а улицы не имеют названий.
Коды Plus должны быть отформатированы как глобальный код или составной код:
- Глобальный код состоит из 4-символьного кода города и 6-символьного или более длинного местного кода. Например, для адреса "1600 Amphitheatre Parkway, Mountain View, CA" глобальный код — "849V", а местный — "CWC8+R9". Затем вы используете весь 10-символьный код Plus Code, чтобы указать значение местоположения как "849VCWC8+R9".
- Составной код состоит из местного кода длиной 6 символов или более, объединенного с указанием местоположения. Например, адрес "450 Serra Mall, Stanford, CA 94305, USA" имеет местный код "CRHJ+C3". Для составного адреса местный код объединяется с городом, штатом, почтовым индексом и страной в форме "CRHJ+C3 Stanford, CA 94305, USA".
Следующий фрагмент кода демонстрирует расчет маршрута с указанием путевых точек начала и конца маршрута с использованием Plus-кодов:
Машинопись
// Use Plus Codes in a directions request. const requestWithPlusCodes = { origin: '849VCWC8+R9', // Mountain View, CA destination: 'CRHJ+C3 Stanford, CA 94305, USA', // Stanford, CA fields: ['path'], };
JavaScript
// Use Plus Codes in a directions request. const requestWithPlusCodes = { origin: '849VCWC8+R9', // Mountain View, CA destination: 'CRHJ+C3 Stanford, CA 94305, USA', // Stanford, CA fields: ['path'], };