Rute adalah jalur yang dapat dilalui antara lokasi awal, atau asal, dan lokasi akhir, atau tujuan. Anda dapat memilih untuk mendapatkan rute untuk berbagai moda transportasi, seperti berjalan kaki, bersepeda, atau berbagai jenis kendaraan. Anda juga dapat meminta detail rute seperti jarak, perkiraan waktu untuk menavigasi rute, perkiraan biaya tol, dan petunjuk langkah demi langkah untuk menavigasi rute.
Lihat contoh kode sumber yang lengkap
Contoh kode berikut menunjukkan cara mendapatkan rute untuk petunjuk arah mengemudi antara dua lokasi.
TypeScript
// 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>Mencoba Contoh
Panggil metode computeRoutes()
untuk meminta rute antara dua lokasi. Contoh berikut menunjukkan cara menentukan
permintaan, lalu memanggil computeRoutes() untuk mendapatkan rute.
// 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);
Pilih kolom yang akan ditampilkan
Saat meminta rute, Anda harus menggunakan mask kolom untuk menentukan informasi yang harus ditampilkan oleh respons. Anda dapat menentukan nama properti class rute di mask kolom.
Penggunaan mask kolom juga memastikan Anda tidak meminta data yang tidak perlu, yang pada gilirannya membantu latensi respons dan menghindari pengembalian informasi yang tidak diperlukan sistem Anda.
Tentukan daftar kolom yang Anda butuhkan dengan menyetel
properti ComputeRoutesRequest.fields, seperti yang ditunjukkan dalam cuplikan berikut:
TypeScript
// 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. };
Menentukan lokasi untuk rute
Untuk menghitung rute, Anda harus menentukan setidaknya lokasi asal rute dan tujuan rute, serta mask kolom. Anda juga dapat menentukan titik jalan perantara di sepanjang rute, dan menggunakan titik jalan untuk melakukan hal lain seperti menambahkan perhentian atau titik terus lewati di sepanjang rute.
Di ComputeRoutesRequest, Anda dapat menentukan lokasi dengan salah satu cara
berikut:
- Place (Pilihan)
- Koordinat lintang/bujur
- String alamat ("Chicago, IL" atau "Darwin, NT, Australia")
- Kode Plus
Anda dapat menentukan lokasi untuk semua titik jalan dalam permintaan dengan cara yang sama, atau Anda dapat mencampurnya. Misalnya, Anda dapat menggunakan koordinat lintang/bujur untuk titik jalan asal dan menggunakan objek Place untuk titik jalan tujuan.
Untuk efisiensi dan akurasi, gunakan objek Place, bukan koordinat lintang/bujur atau string alamat. ID tempat secara unik eksplisit dan memberikan manfaat geocoding untuk perutean, seperti titik akses dan variabel traffic. Cara ini membantu menghindari situasi berikut yang dapat terjadi akibat cara lain untuk menentukan lokasi:
- Menggunakan koordinat lintang/bujur dapat menyebabkan lokasi dipaskan ke jalan terdekat dengan koordinat tersebut - yang mungkin bukan titik akses ke properti, atau bahkan jalan yang dengan cepat atau aman mengarah ke tujuan.
- String alamat harus di-geocode terlebih dahulu oleh Routes API untuk mengonversinya menjadi koordinat garis lintang/bujur sebelum dapat menghitung rute. Konversi ini dapat memengaruhi performa.
Menentukan lokasi sebagai objek Place (disarankan)
Untuk menentukan lokasi menggunakan Tempat, buat instance Place baru. Cuplikan
berikut menunjukkan pembuatan instance Place baru untuk origin
dan destination, lalu menggunakannya dalam 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 = { 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. };
Koordinat lintang/bujur
Untuk menentukan lokasi sebagai koordinat lintang/bujur, buat instance
google.maps.LatLngLiteral, google.maps.LatLngAltitude, atau
google.maps.LatLngAltitudeLiteral baru. Cuplikan berikut menunjukkan pembuatan
instance google.maps.LatLngLiteral baru untuk origin dan destination,
lalu menggunakannya dalam computeRoutesRequest:
TypeScript
// 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'], };
String alamat
String alamat adalah alamat literal yang diwakili oleh string (seperti "1600 Amphitheatre Parkway, Mountain View, CA"). Geocoding adalah proses konversi string alamat menjadi koordinat lintang dan bujur (seperti lintang 37.423021 dan bujur -122.083739).
Saat Anda meneruskan string alamat sebagai lokasi titik jalan, library Routes secara internal melakukan geocoding pada string untuk mengonversinya menjadi koordinat lintang dan bujur.
Cuplikan berikut menunjukkan pembuatan ComputeRoutesRequest dengan string
alamat untuk origin dan 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'], };
Menetapkan region untuk alamat
Jika Anda meneruskan string alamat yang tidak lengkap sebagai lokasi titik jalan, API mungkin menggunakan koordinat lintang/bujur geocode yang salah. Misalnya, Anda membuat permintaan yang menentukan "Toledo" sebagai asal dan "Madrid" sebagai tujuan untuk rute mengemudi:
// Define a request with an incomplete address string. const request = { origin: 'Toledo', destination: 'Madrid', };
Dalam contoh ini, "Toledo" ditafsirkan sebagai kota di negara bagian Ohio di Amerika Serikat, bukan di Spanyol. Oleh karena itu, permintaan menampilkan array kosong, yang berarti tidak ada rute.
Anda dapat mengonfigurasi API untuk menampilkan hasil yang dibiaskan ke wilayah tertentu dengan menyertakan parameter regionCode. Parameter ini menentukan kode wilayah sebagai nilai dua karakter ccTLD ("domain level teratas"). Sebagian besar kode ccTLD identik dengan kode ISO 3166-1, dengan beberapa pengecualian. Misalnya, ccTLD Inggris Raya adalah "uk" (.co.uk), sedangkan kode ISO 3166-1-nya adalah "gb" (secara teknis untuk entitas "Britania Raya dan Irlandia Utara").
Permintaan rute untuk "Toledo" ke "Madrid" yang menyertakan parameter regionCode akan menampilkan hasil yang sesuai karena "Toledo" ditafsirkan sebagai kota di Spanyol:
const request = { origin: 'Toledo', destination: 'Madrid', region: 'es', // Specify the region code for Spain. };
Plus Code
Banyak orang tidak memiliki alamat yang tepat, sehingga mereka kesulitan menerima pengiriman. Atau, orang yang memiliki alamat mungkin lebih suka menerima pengiriman di lokasi yang lebih spesifik, seperti pintu belakang atau area bongkar muat.
Plus Codes berfungsi seperti alamat untuk orang atau tempat yang belum memiliki alamat sebenarnya. Daripada alamat dengan nama jalan dan nomor, Plus Codes didasarkan pada koordinat lintang/bujur, dan ditampilkan sebagai angka dan huruf.
Google mengembangkan Plus Codes untuk memberikan manfaat alamat kepada semua orang dan semuanya. Kode Plus adalah referensi lokasi yang dienkode, yang berasal dari koordinat lintang/bujur, yang mewakili area: 1/8000 derajat x 1/8000 derajat (sekitar 14 m x 14 m di khatulistiwa) atau lebih kecil. Anda dapat menggunakan Plus Codes sebagai pengganti alamat di tempat yang tidak memiliki alamat atau di tempat yang bangunannya tidak diberi nomor atau jalannya tidak diberi nama.
Plus Codes harus diformat sebagai kode global atau kode gabungan:
- kode global terdiri dari kode area berisi 4 karakter dan kode lokal berisi 6 karakter atau lebih. Misalnya, untuk alamat "1600 Amphitheatre Parkway, Mountain View, CA", kode globalnya adalah "849V" dan kode lokalnya adalah "CWC8+R9". Kemudian, Anda menggunakan seluruh 10 karakter Kode Plus untuk menentukan nilai lokasi sebagai "849VCWC8+R9".
- kode majemuk terdiri dari kode lokal berisi 6 karakter atau lebih yang digabungkan dengan lokasi yang eksplisit. Misalnya, alamat "450 Serra Mall, Stanford, CA 94305, USA" memiliki kode lokal "CRHJ+C3". Untuk alamat gabungan, gabungkan kode lokal dengan kota, negara bagian, kode pos, dan bagian negara dari alamat dalam bentuk "CRHJ+C3 Stanford, CA 94305, USA".
Cuplikan berikut menunjukkan penghitungan rute dengan menentukan titik jalan untuk asal rute dan tujuan menggunakan Kode Plus:
TypeScript
// 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'], };