Trasa to ścieżka, którą można nawigować, między lokalizacją początkową (miejscem początkowym) a lokalizacją końcową 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 podróży, przewidywane opłaty drogowe i szczegółowe instrukcje nawigacji.
Zobacz pełny przykładowy kod źródłowy
Poniższy przykładowy kod pokazuje, jak uzyskać wskazówki 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 trasę między 2 lokalizacjami, wywołaj metodę computeRoutes(). Poniższy przykład pokazuje, jak zdefiniować żądanie, a następnie wywołać metodę computeRoutes() w celu uzyskania trasy.
// 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);
Wybieranie pól do zwrócenia
Gdy prosisz o trasę, musisz użyć maski pola, aby określić, jakie informacje powinna zawierać odpowiedź powinna zawierać. W masce pola możesz określić nazwy właściwości klasy Route.
Użycie maski pola zapewnia też, że nie będziesz prosić o niepotrzebne dane, co z kolei pomaga zmniejszyć opóźnienie odpowiedzi i uniknąć zwracania informacji, których Twój system nie potrzebuje.
Określ listę potrzebnych pól, ustawiając
ComputeRoutesRequest.fields
właściwość, jak pokazano w tym fragmencie:
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 na trasie
Aby obliczyć trasę, musisz podać co najmniej lokalizacje miejsca początkowego i docelowego oraz maskę pola. Możesz też określić punkty pośrednie na trasie i używać punktów pośrednich do innych celów, np. do dodawania przystanków lub punktów przejazdu na trasie.
W ComputeRoutesRequest możesz określić lokalizację na jeden z tych
sposobów:
- Miejsce (preferowane)
- Współrzędne geograficzne
- Ciąg znaków adresu ("Chicago, IL" lub "Darwin, NT, Australia")
- Plus Code
Możesz określić lokalizacje dla wszystkich punktów pośrednich w żądaniu w ten sam sposób lub je mieszać. Możesz na przykład użyć współrzędnych geograficznych dla punktu początkowego i obiektu Place dla punktu docelowego.
Aby zwiększyć wydajność i dokładność, używaj obiektów Place zamiast współrzędnych geograficznych lub ciągów znaków adresu. Identyfikatory miejsc są jednoznaczne i zapewniają korzyści geokodowania na potrzeby wyznaczania trasy takie jak punkty dostępu i zmienne ruchu. Pomagają one uniknąć sytuacji, które mogą wystąpić w przypadku innych sposobów określania lokalizacji:
- Użycie współrzędnych geograficznych może spowodować, że lokalizacja zostanie przyciągnięta do najbliższej drogi która może nie być punktem dostępu do nieruchomości ani nawet drogą, która szybko lub bezpiecznie prowadzi do miejsca docelowego.
- Aby można było obliczyć trasę, ciągi znaków adresu muszą najpierw zostać geokodowane przez interfejs Routes API w celu przekonwertowania ich na współrzędne geograficzne. Ta konwersja może wpłynąć na wydajność.
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 geograficzne
Aby określić lokalizację jako współrzędne geograficzne, utwórz nową instancję
google.maps.LatLngLiteral, google.maps.LatLngAltitude, lub
google.maps.LatLngAltitudeLiteral. Poniższy fragment kodu pokazuje, jak utworzyć
nowe google.maps.LatLngLiteral instancje 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 znaków adresu
Ciągi znaków adresu to dosłowne adresy reprezentowane przez ciąg znaków (np. „Rynek Główny 12, 31-042 Kraków”). Geokodowanie to proces przekształcania ciągu znaków adresu na współrzędne geograficzne (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 znaków, aby przekształcić go na współrzędne geograficzne.
Poniższy fragment kodu pokazuje, jak utworzyć ComputeRoutesRequest z ciągiem znaków 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 przekażesz niepełny ciąg znaków adresu, interfejs API może użyć nieprawidłowych geokodowanych współrzędnych geograficznych. Na przykład wysyłasz żądanie, w którym jako miejsce początkowe podajesz „Toledo”, a jako miejsce docelowe „Madryt”:
// 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 z uwzględnieniem określonego regionu, dodając parametr regionCode. Ten parametr określa kod regionu jako a ccTLD („domena najwyższego poziomu”) 2-znakową wartość. Większość kodów ccTLD jest identyczna z kodami ISO 3166-1, z kilkoma wyjątkami. Na przykład ccTLD Wielkiej Brytanii to „uk” (.co.uk), a jej kod ISO 3166-1 code to „gb” (technicznie dla podmiotu „Zjednoczone Królestwo Wielkiej Brytanii i Irlandii Północnej”).
Żądanie wskazówek dojazdu z "Toledo" do "Madrytu", które 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 odbieranie przesyłek. Osoby, które mają adres, mogą też woleć odbierać przesyłki w bardziej konkretnych lokalizacjach, np. przy tylnym wejściu lub przy rampie.
Kody plus są jak adresy dla osób lub miejsc, które nie mają rzeczywistego adresu. Zamiast adresów z nazwą ulicy i numerem kody plus są oparte na współrzędnych geograficznych i wyświetlane jako cyfry i litery.
Google opracowało kody plus aby zapewnić wszystkim korzyści wynikające z posiadania adresu. Kod plus to zakodowany odnośnik do lokalizacji, który jest wyprowadzany ze współrzędnych geograficznych i reprezentuje obszar: 1/8000 stopnia na 1/8000 stopnia (około 14 m x 14 m na równiku) lub mniejszy. Możesz używać kodów plus jako zamiennika adresów w miejscach, w których nie istnieją, lub w których budynki nie są numerowane, a ulice nie mają nazw.
Kody plus muszą być sformatowane jako kod globalny lub kod złożony:
- Kod globalny składa się z 4-znakowego kodu obszaru i 6-znakowego lub dłuższego kodu lokalnego. Na przykład dla adresu „Rynek Główny 12, 31-042 Kraków” kod globalny to „849V”, a kod lokalny to „CWC8+R9”. Następnie używasz całego 10-znakowego kodu plus aby określić wartość lokalizacji jako "849VCWC8+R9".
- Kod złożony składa się z 6-znakowego lub dłuższego kodu lokalnego połączonego z jawną lokalizacją. Na przykład adres „Rynek Główny 12, 31-042 Kraków” ma kod lokalny „CRHJ+C3”. W przypadku adresu złożonego połącz kod lokalny z miastem, województwem, kodem pocztowym i częścią adresu dotyczącą kraju w formacie "CRHJ+C3 Kraków, Małopolskie, 31-042, Polska".
Poniższy fragment kodu pokazuje, jak obliczyć trasę, określając punkt pośredni dla miejsca początkowego i docelowego za pomocą kodów plus:
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'], };