Маршрут – это путь между начальной и конечной точками. Вы можете выбрать маршрут для разных видов транспорта, например пешком, на велосипеде или на автомобиле. Вы также можете запросить информацию о маршруте, например расстояние, примерное время в пути, ожидаемые платные участки и пошаговые инструкции.
Посмотреть полный пример исходного кода
В следующем примере кода показано, как получить маршрут для автомобильного маршрута между двумя местоположениями.
TypeScript
// Initialize and add the map. let map: google.maps.Map; let mapPolylines: google.maps.Polyline[] = []; const center = { lat: 37.447646, lng: -122.113878 }; // Palo Alto, CA // Initialize and add the map. async function init(): Promise<void> { // Request the needed libraries. const [{ Map }, { Place }, { Route }] = await Promise.all([ google.maps.importLibrary('maps'), google.maps.importLibrary('places'), google.maps.importLibrary('routes'), ]); map = new Map(document.getElementById('map')!, { zoom: 12, 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'], }; console.log({ requestWithAddressStrings }); // 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: google.maps.routes.ComputeRoutesRequest = { origin: originPlaceInstance, destination: destinationPlaceInstance, fields: ['path'], // Request fields needed to draw polylines. }; console.log({ requestWithPlaceIds }); // 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: google.maps.routes.ComputeRoutesRequest = { origin: originLatLng, destination: destinationLatLng, fields: ['path'], }; console.log({ requestWithLatLngs }); // Use Plus Codes in a directions request. const requestWithPlusCodes: google.maps.routes.ComputeRoutesRequest = { origin: '849VCWC8+R9', // Mountain View, CA destination: 'CRHJ+C3 Stanford, CA 94305, USA', // Stanford, CA fields: ['path'], }; console.log({ requestWithPlusCodes }); // Define a routes request. const request: google.maps.routes.ComputeRoutesRequest = { 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 } = await Route.computeRoutes(request); // Use createPolylines to create polylines for the route. if (!routes) { console.warn('No routes found.'); return; } 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.map = 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. void fitMapToPath(routes[0].path!); } // Helper function to fit the map to the path. async function fitMapToPath(path: google.maps.LatLngLiteral[]) { const { LatLngBounds } = await google.maps.importLibrary('core'); const bounds = new LatLngBounds(); path.forEach((point) => { bounds.extend(point); }); map.fitBounds(bounds); } void init();
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 init() { // Request the needed libraries. const [{ Map }, { Place }, { Route }] = await Promise.all([ google.maps.importLibrary('maps'), google.maps.importLibrary('places'), google.maps.importLibrary('routes'), ]); map = new Map(document.getElementById('map'), { zoom: 12, 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'], }; console.log({ requestWithAddressStrings }); // 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. }; console.log({ requestWithPlaceIds }); // 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'], }; console.log({ requestWithLatLngs }); // 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'], }; console.log({ requestWithPlusCodes }); // 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 } = await Route.computeRoutes(request); // Use createPolylines to create polylines for the route. if (!routes) { console.warn('No routes found.'); return; } 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.map = 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. void 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); } void init();
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>
<script>
// prettier-ignore
(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: "GOOGLE_MAPS_API_KEY"
});
</script>
</head>
<body>
<div id="map"></div>
</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);
Как выбрать поля для возврата
При запросе маршрута необходимо использовать маску поля, чтобы указать, какую информацию должен вернуть ответ. В маске поля можно указать названия свойств класса маршрута.
Маска поля также позволяет не запрашивать ненужные данные, что помогает снизить задержку ответа и избежать возврата информации, которая не нужна вашей системе.
Укажите список нужных полей, задав свойство ComputeRoutesRequest.fields, как показано в следующем фрагменте кода:
TypeScript
// Define a routes request. const request: google.maps.routes.ComputeRoutesRequest = { 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 можно указать местоположение одним из следующих способов:
- Место (предпочтительно)
- Координаты широты и долготы
- Строка адреса ("Чикаго, Иллинойс" или "Дарвин, Северная территория, Австралия")
- Код Plus
Вы можете указать местоположения для всех путевых точек в запросе одним и тем же способом или использовать разные способы. Например, для исходной путевой точки можно использовать координаты широты и долготы, а для конечной – объект Place.
Для эффективности и точности используйте объекты Place вместо координат широты и долготы или строк адреса. Идентификаторы мест уникальны и позволяют использовать геокодирование для построения маршрутов, например для определения точек доступа и переменных трафика. Они помогают избежать следующих ситуаций, которые могут возникнуть при других способах указания местоположения:
- При использовании координат широты и долготы местоположение может быть привязано к ближайшей дороге, которая не всегда является подъездным путем к объекту или даже безопасным и быстрым способом добраться до него.
- Чтобы рассчитать маршрут, сначала необходимо преобразовать строки адресов в координаты широты и долготы с помощью Routes API. Это может повлиять на эффективность.
Как указать местоположение в виде объекта Place (рекомендуется)
Чтобы указать местоположение с помощью объекта Place, создайте новый экземпляр Place. В следующем фрагменте кода показано, как создать новые экземпляры Place для origin и destination, а затем использовать их в ComputeRoutesRequest:
TypeScript
// 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: google.maps.routes.ComputeRoutesRequest = { 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:
TypeScript
// 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: google.maps.routes.ComputeRoutesRequest = { 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).
Когда вы передаете строку адреса в качестве местоположения путевой точки, библиотека маршрутов выполняет внутреннее геокодирование строки, чтобы преобразовать ее в координаты широты и долготы.
Во фрагменте кода ниже показано, как создать объект ComputeRoutesRequest со строкой адреса для origin и destination:
TypeScript
// 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 Code
У многих людей нет точного адреса, поэтому им сложно получать посылки. Кроме того, пользователи с адресом могут предпочитать получать посылки в определенных местах, например у заднего входа или на погрузочной платформе.
Коды Plus Code – это своего рода адреса для людей и мест, у которых нет обычных адресов. В отличие от обычных адресов, в которых указываются названия улиц и номера домов, коды Plus Code основаны на координатах широты и долготы и состоят из цифр и букв.
Google разработал коды Plus Code, чтобы адреса были доступны всем. Код Plus Code – это закодированная ссылка на местоположение, полученная на основе координат широты и долготы. Она обозначает область размером 1/8000 градуса на 1/8000 градуса (примерно 14 x 14 м на экваторе) или меньше. Коды Plus Code можно использовать в качестве замены почтовым адресам там, где эти адреса не существуют (здания не пронумерованы или улицам не присвоены названия).
Коды Plus Code должны быть отформатированы как глобальный или составной код:
- Глобальный код состоит из четырехзначного кода зоны и шестизначного или более длинного местного кода. Например, для адреса "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 Codes:
TypeScript
// Use Plus Codes in a directions request. const requestWithPlusCodes: google.maps.routes.ComputeRoutesRequest = { 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'], };