Маршрут — это навигируемый путь между начальной точкой (источником) и конечной точкой (пунктом назначения). Вы можете получить маршрут для различных видов транспорта, например, пешком, на велосипеде или на разных типах транспортных средств. Вы также можете запросить информацию о маршруте, такую как расстояние, предполагаемое время в пути, ожидаемые сборы и пошаговые инструкции по его прохождению.
Посмотреть полный исходный код примера
В следующем примере кода показано, как получить маршрут проезда между двумя точками.
Машинопись
// 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.422000, 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.422000, 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 Routes и преобразованы в координаты широты и долготы. Это преобразование может повлиять на производительность.
Укажите местоположение как объект 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.422000, 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.422000, 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. };
Плюс Код
У многих людей нет точного адреса, что может затруднить получение посылок. Или же те, у кого есть адрес, могут предпочесть получать посылки в более определённых местах, например, у заднего входа или на погрузочной площадке.
Plus-коды — это своего рода адреса для людей или мест, у которых нет фактического адреса. Вместо адресов с названиями улиц и номерами домов, Plus-коды основаны на координатах широты и долготы и отображаются в виде цифр и букв.
Компания Google разработала Plus-коды , чтобы предоставить всем и каждому возможность пользоваться адресами. Plus-код — это закодированная ссылка на местоположение, полученная на основе координат широты и долготы, которая представляет область размером 1/8000 градуса на 1/8000 градуса (примерно 14 м на экваторе) или меньше. Вы можете использовать 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'], };