Маршрут

Разработчики из Европейской экономической зоны (ЕЭЗ)

Маршрут – это путь между начальной точкой (пунктом отправления) и конечной точкой (пунктом назначения). Вы можете выбрать маршрут для разных способов передвижения, например пешком, на велосипеде или на разных типах транспортных средств. Вы также можете запросить сведения о маршруте, такие как расстояние, расчетное время в пути, ожидаемая плата за проезд и пошаговые инструкции по навигации.

Посмотреть полный пример исходного кода

В следующем примере кода показано, как получить автомобильный маршрут между двумя местоположениями.

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(), чтобы получить маршрут. computeRoutes() – это статический метод класса Route, поэтому вызывайте Route.computeRoutes(request) напрямую. В запросе также должно быть задано свойство fields для маски поля ответа.

  // 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',
    fields: ['path'], // Required: response field mask.
  };

  // Call the computeRoutes() method to get routes.
  const {routes} = await Route.computeRoutes(request);
    

Чтобы нарисовать маршрут на карте, вызовите createPolylines() для маршрута, запрошенного с полем path. Подробнее о том, как показывать ломаные линии на карте…

Выберите поля, которые нужно вернуть

При запросе маршрута необходимо использовать маску поля, чтобы указать, какую информацию должен возвращать ответ. В маске поля можно указать названия свойств класса Route.

Маски полей также помогают не запрашивать ненужные данные, что позволяет сократить время ответа и избежать возврата информации, которая не нужна вашей системе.

Укажите список нужных полей, задав свойство 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 можно указать местоположение одним из следующих способов:

Вы можете указать местоположения для всех путевых точек в запросе одним и тем же способом или комбинировать их. Например, для начальной путевой точки можно использовать координаты широты и долготы, а для конечной – объект 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).

Если вы передаете строку адреса в качестве местоположения путевой точки, библиотека Routes выполняет геокодирование строки, чтобы преобразовать ее в координаты широты и долготы.

В следующем фрагменте кода показано, как создать объект 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 – это закодированная ссылка на местоположение на основе координат широты и долготы, которая представляет область: 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".
  • Составной код содержит не менее шести знаков местного кода с данными о местоположении. Например, для адреса "450 Serra Mall, Stanford, CA 94305, USA" локальный код будет "CRHJ+C3". Для составного адреса объедините местный код с городом, штатом, почтовым индексом и страной в формате "CRHJ+C3 Stanford, CA 94305, USA".

В следующем фрагменте кода показано, как рассчитать маршрут, указав путевую точку для начальной и конечной точек маршрута с помощью кодов Plus Code.

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'],
};