Wyznacz trasę

Deweloperzy z Europejskiego Obszaru Gospodarczego (EOG)

Trasa to ścieżka, którą można się poruszać między lokalizacją początkową (miejscem wyjazdu) a lokalizacją końcową (miejscem docelowym). Możesz wybrać trasę dla różnych środków transportu, takich jak pieszo, rowerem lub różnymi typami pojazdów. Możesz też poprosić o szczegóły trasy, takie jak odległość, szacowany czas przejazdu, oczekiwane opłaty i szczegółowe instrukcje nawigacji.

Zobacz kompletny przykładowy kod źródłowy

Poniższy przykładowy kod pokazuje, jak uzyskać trasę ze wskazówkami dojazdu między 2 lokalizacjami.

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>

Aby poprosić o wyznaczenie trasy między 2 lokalizacjami, wywołaj metodę computeRoutes(). W przykładzie poniżej pokazujemy, jak zdefiniować żądanie, a następnie wywołać metodę computeRoutes(), aby uzyskać trasę. computeRoutes() to metoda statyczna klasy Route, więc wywołaj bezpośrednio Route.computeRoutes(request). Żądanie musi też ustawić właściwość fields na maskę pola odpowiedzi.

  // 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);
    

Aby narysować trasę na mapie, wywołaj createPolylines() na trasie, o którą poproszono w polu path. Zobacz Wyświetlanie linii łamanych na mapie.

Wybierz pola, które mają być zwracane

Gdy wysyłasz żądanie trasy, musisz użyć maski pola, aby określić, jakie informacje ma zwracać odpowiedź. W masce pola możesz podać nazwy właściwości klasy Route.

Użycie maski pola gwarantuje też, że nie będziesz prosić o niepotrzebne dane, co z kolei pomaga zmniejszyć opóźnienie odpowiedzi i pozwala uniknąć zwracania informacji, których Twój system nie potrzebuje.

Określ listę potrzebnych pól, ustawiając właściwość ComputeRoutesRequest.fields, jak pokazano w tym fragmencie kodu:

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.
};

Określanie lokalizacji trasy

Aby obliczyć trasę, musisz określić co najmniej lokalizacje punktu początkowego i docelowego oraz maskę pola. Możesz też określić punkty pośrednie na trasie i używać ich do wykonywania innych czynności, takich jak dodawanie przystanków lub punktów przejazdu na trasie.

W ComputeRoutesRequest możesz określić lokalizację na jeden z tych sposobów:

Możesz określić lokalizacje wszystkich punktów pośrednich w żądaniu w ten sam sposób lub je połączyć. Możesz na przykład użyć współrzędnych geograficznych dla punktu początkowego i obiektu Place dla punktu docelowego.

Aby zapewnić wydajność i dokładność, używaj obiektów Place zamiast współrzędnych szerokości i długości geograficznej lub ciągów adresowych. Identyfikatory miejsc są jednoznaczne i zapewniają korzyści związane z geokodowaniem na potrzeby wyznaczania trasy, takie jak punkty dostępu i zmienne dotyczące ruchu. Pomagają uniknąć tych sytuacji, które mogą wystąpić, gdy lokalizacja jest określana w inny sposób:

  • Użycie współrzędnych szerokości i długości geograficznej może spowodować, że lokalizacja zostanie przyciągnięta do drogi najbliższej tym współrzędnym, która może nie być punktem dostępu do obiektu, a nawet drogą, która szybko lub bezpiecznie prowadzi do miejsca docelowego.
  • Ciągi adresów muszą najpierw zostać poddane geokodowaniu przez interfejs Routes API, aby można było je przekonwertować na współrzędne szerokości i długości geograficznej przed obliczeniem trasy. Ta konwersja może mieć wpływ na skuteczność.

Określanie lokalizacji jako obiektu Place (preferowane)

Aby określić lokalizację za pomocą miejsca, utwórz nową instancję Place. Poniższy fragment kodu pokazuje, jak utworzyć nowe instancje Place dla origin i destination, a następnie użyć ich w 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.
};

Współrzędne szerokości i długości geograficznej

Aby określić lokalizację jako współrzędne szerokości i długości geograficznej, utwórz nową instancję google.maps.LatLngLiteral, google.maps.LatLngAltitude lub google.maps.LatLngAltitudeLiteral. Poniższy fragment kodu pokazuje, jak utworzyć nowe instancje google.maps.LatLngLiteral dla origin i destination, a następnie użyć ich w 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'],
};

Ciąg adresu

Ciągi adresów to adresy dosłowne reprezentowane przez ciąg znaków (np. „1600 Amphitheatre Parkway, Mountain View, CA”). Geokodowanie to proces przekształcania ciągu znaków adresu na współrzędne szerokości i długości geograficznej (np. szerokość geograficzna 37.423021 i długość geograficzna -122.083739).

Gdy przekazujesz ciąg znaków adresu jako lokalizację punktu pośredniego, biblioteka Routes wewnętrznie geokoduje ten ciąg, aby przekonwertować go na współrzędne szerokości i długości geograficznej.

Poniższy fragment kodu pokazuje, jak utworzyć ComputeRoutesRequest z ciągiem adresu dla origin i 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'],
};

Ustawianie regionu dla adresu

Jeśli jako lokalizację punktu pośredniego podasz niepełny ciąg znaków adresu, interfejs API może użyć nieprawidłowych współrzędnych szerokości i długości geograficznej. Jeśli na przykład wyślesz żądanie, w którym jako miejsce początkowe podasz „Toledo”, a jako miejsce docelowe „Madryt”, otrzymasz trasę dojazdu:

// Define a request with an incomplete address string.
const request = {
  origin: 'Toledo',
  destination: 'Madrid',
};
    

W tym przykładzie „Toledo” jest interpretowane jako miasto w stanie Ohio w Stanach Zjednoczonych, a nie w Hiszpanii. Dlatego żądanie zwraca pustą tablicę, co oznacza, że nie ma żadnych tras.

Możesz skonfigurować interfejs API tak, aby zwracał wyniki faworyzujące dany region, dodając parametr regionCode. Ten parametr określa kod regionu jako 2-znakową wartość ccTLD („domena najwyższego poziomu”). Większość kodów ccTLD jest identyczna z kodami ISO 3166-1, z kilkoma wyjątkami. Na przykład domena ccTLD Wielkiej Brytanii to „uk” (.co.uk), a jej kod ISO 3166-1 to „gb” (technicznie dla podmiotu „Zjednoczone Królestwo Wielkiej Brytanii i Irlandii Północnej”).

Prośba o wskazówki dojazdu z „Toledo” do „Madrytu”, która zawiera parametr regionCode, zwraca odpowiednie wyniki, ponieważ „Toledo” jest interpretowane jako miasto w Hiszpanii:

const request = {
  origin: 'Toledo',
  destination: 'Madrid',
  region: 'es', // Specify the region code for Spain.
};
    

Plus Code

Wiele osób nie ma dokładnego adresu, co może utrudniać im otrzymywanie przesyłek. Z kolei osoby, które mają adres, mogą preferować odbiór przesyłek w bardziej konkretnych miejscach, takich jak wejście od tyłu lub rampa załadunkowa.

Kody Plus są jak adresy ulic dla osób lub miejsc, które nie mają rzeczywistego adresu. Zamiast adresów z nazwami ulic i numerami domów kody Plus wykorzystują współrzędne szerokości i długości geograficznej i są wyświetlane jako ciągi cyfr i liter.

Google opracowało Plus Codes, aby każdy mógł korzystać z zalet adresów. Plus Code to zakodowane odniesienie do lokalizacji, które pochodzi ze współrzędnych szerokości i długości geograficznej i reprezentuje obszar o wymiarach 1/8000 stopnia na 1/8000 stopnia (około 14 m na 14 m na równiku) lub mniejszy. Możesz używać kodów Plus Codes zamiast adresów ulic w miejscach, gdzie ich nie ma, gdzie budynki nie są ponumerowane lub ulice nie mają nazw.

Kody Plus Code muszą być sformatowane jako kod globalny lub kod złożony:

  • Kod globalny składa się z 4-znakowego numeru kierunkowego i 6-znakowego lub dłuższego kodu lokalnego. Na przykład w przypadku adresu „1600 Amphitheatre Parkway, Mountain View, CA” kod globalny to „849V”, a kod lokalny to „CWC8+R9”. Następnie używasz całego 10-znakowego plus kodu, aby określić wartość lokalizacji jako „849VCWC8+R9”.
  • kod złożony składa się z kodu lokalnego o długości co najmniej 6 znaków połączonego z wyraźną lokalizacją. Na przykład adres „450 Serra Mall, Stanford, CA 94305, USA” ma kod lokalny „CRHJ+C3”. W przypadku adresu złożonego połącz kod lokalny z miastem, stanem, kodem pocztowym i krajem w formacie „CRHJ+C3 Stanford, CA 94305, USA”.

Poniższy fragment kodu pokazuje, jak obliczyć trasę, określając punkt na trasie dla punktu początkowego i docelowego trasy za pomocą kodów 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'],
};