Rota alın

Avrupa Ekonomik Alanı'ndaki (AEA) geliştiriciler

Rota, başlangıç konumu veya başlangıç noktası ile bitiş konumu ya da hedef arasında gezinilebilir bir yoldur. Yürüyüş, bisiklet veya farklı araç türleri gibi farklı ulaşım şekilleri için rota almayı seçebilirsiniz. Ayrıca mesafe, rotada gezinmek için tahmini süre, beklenen ücretler ve rotada gezinmek için adım adım talimatlar gibi rota ayrıntılarını da isteyebilirsiniz.

Eksiksiz örnek kaynak kodunu inceleyin

Aşağıdaki kod örneğinde, iki konum arasında arabayla yol tarifi için nasıl rota alınacağı gösterilmektedir.

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>

Örneği deneyin

İki konum arasında rota isteğinde bulunmak için computeRoutes() yöntemini çağırın. Aşağıdaki örnekte, bir isteğin nasıl tanımlanacağı ve ardından rota almak için computeRoutes() yönteminin nasıl çağrılacağı gösterilmektedir. computeRoutes(), Route sınıfının statik bir yöntemidir. Bu nedenle doğrudan Route.computeRoutes(request) yöntemini çağırın. İstek, fields özelliğini bir yanıt alanı maskesine de ayarlamalıdır.

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

Rotayı haritada çizmek için path alanıyla istediğiniz bir rotada createPolylines() yöntemini çağırın. Haritada çoklu çizgiler görüntüleme başlıklı makaleyi inceleyin.

Döndürülecek alanları seçin

Rota isteğinde bulunurken yanıtın hangi bilgileri döndürmesi gerektiğini belirtmek için alan maskesi kullanmanız gerekir. Alan maskesinde Route sınıfı özelliklerinin adlarını belirtebilirsiniz.

Alan maskesi kullanmak, gereksiz veri istememenizi de sağlar. Bu da yanıt gecikmesine yardımcı olur ve sisteminizin ihtiyaç duymadığı bilgilerin döndürülmesini önler.

Aşağıdaki snippet'te gösterildiği gibi ComputeRoutesRequest.fields özelliğini ayarlayarak ihtiyacınız olan alanların listesini belirtin:

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

Rota için konumları belirtme

Bir rotayı hesaplamak için en azından rotanın başlangıç ve hedef konumlarını ve bir alan maskesi belirtmeniz gerekir. Ayrıca, bir rota boyunca ara yol noktaları belirtebilir ve yol noktalarını, rota boyunca duraklar veya geçiş noktaları eklemek gibi başka işlemler yapmak için kullanabilirsiniz.

ComputeRoutesRequest bölümünde, aşağıdaki yöntemlerden birini kullanarak konum belirtebilirsiniz:

Bir istekteki tüm ara noktaların konumlarını aynı şekilde belirtebilir veya farklı yöntemleri bir arada kullanabilirsiniz. Örneğin, başlangıç ara noktası için enlem/boylam koordinatlarını, hedef ara nokta için ise bir Place nesnesini kullanabilirsiniz.

Verimlilik ve doğruluk için enlem/boylam koordinatları veya adres dizeleri yerine Place nesnelerini kullanın. Yer kimlikleri benzersiz şekilde açıktır ve erişim noktaları ve trafik değişkenleri gibi rotalar için coğrafi kodlama avantajları sağlar. Konum belirtmenin diğer yollarından kaynaklanabilecek aşağıdaki durumların önlenmesine yardımcı olurlar:

  • Enlem/boylam koordinatlarının kullanılması, konumun bu koordinatlara en yakın yola sabitlenmesine neden olabilir. Bu yol, tesise erişim noktası olmayabilir, hatta hedefe hızlı veya güvenli bir şekilde ulaşan bir yol bile olmayabilir.
  • Adres dizelerinin, rota hesaplanmadan önce enlem/boylam koordinatlarına dönüştürülmesi için Routes API tarafından coğrafi olarak kodlanması gerekir. Bu dönüşüm performansı etkileyebilir.

Konumu Place nesnesi olarak belirtme (tercih edilen)

Bir yer kullanarak konum belirtmek için yeni bir Place örneği oluşturun. Aşağıdaki snippet'te, origin ve destination için yeni Place örneklerinin nasıl oluşturulduğu ve ardından bunların bir ComputeRoutesRequest içinde nasıl kullanıldığı gösterilmektedir:

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

Enlem/boylam koordinatları

Bir konumu enlem/boylam koordinatları olarak belirtmek için yeni bir google.maps.LatLngLiteral, google.maps.LatLngAltitude veya google.maps.LatLngAltitudeLiteral örneği oluşturun. Aşağıdaki snippet'te, origin ve destination için yeni google.maps.LatLngLiteral örneklerinin nasıl oluşturulduğu ve ardından bunların bir computeRoutesRequest içinde nasıl kullanıldığı gösterilmektedir:

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

Adres dizesi

Adres dizeleri, bir dizeyle temsil edilen gerçek adreslerdir (ör. "1600 Amphitheatre Parkway, Mountain View, CA"). Coğrafi kodlama, bir adres dizesini enlem ve boylam koordinatlarına (ör. enlem 37.423021 ve boylam -122.083739) dönüştürme işlemidir.

Bir ara noktanın konumu olarak adres dizesi ilettiğinizde Rotalar kitaplığı, dizeyi enlem ve boylam koordinatlarına dönüştürmek için dahili olarak coğrafi kodlar.

Aşağıdaki snippet'te, origin ve destination için adres dizesi içeren bir ComputeRoutesRequest oluşturma işlemi gösterilmektedir:

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

Adres için bölgeyi ayarlama

Bir ara noktanın konumu olarak eksik bir adres dizesi iletirseniz API, yanlış coğrafi kodlu enlem/boylam koordinatlarını kullanabilir. Örneğin, bir sürüş rotası için başlangıç noktasını "Toledo" ve varış noktasını "Madrid" olarak belirten bir istekte bulunursunuz:

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

Bu örnekte "Toledo", İspanya'da değil, ABD'nin Ohio eyaletinde bir şehir olarak yorumlanır. Bu nedenle, istek boş bir dizi döndürür. Bu da rota olmadığı anlamına gelir.

API'yi, regionCode parametresini ekleyerek belirli bir bölgeye yönelik sonuca ağırlık verme döndürecek şekilde yapılandırabilirsiniz. Bu parametre, bölge kodunu iki karakterli bir ccTLD ("üst düzey alan") değeri olarak belirtir. Çoğu ccTLD kodu, bazı önemli istisnalar dışında ISO 3166-1 kodlarıyla aynıdır. Örneğin, Birleşik Krallık'ın ccTLD'si "uk" (.co.uk) iken ISO 3166-1 kodu "gb"dir (teknik olarak "Büyük Britanya ve Kuzey İrlanda Birleşik Krallığı" tüzel kişiliği için).

regionCode parametresini içeren "Toledo"dan "Madrid"e yol tarifi isteği, "Toledo" İspanya'da bir şehir olarak yorumlandığı için uygun sonuçlar döndürür:

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

Plus Code

Birçok kişinin tam adresi yoktur. Bu durum, teslimat almalarını zorlaştırabilir. Adresi olan kişiler de teslimatları arka giriş veya yükleme alanı gibi daha belirli konumlarda kabul etmeyi tercih edebilir.

Plus Code'lar, gerçek bir adresi olmayan kişiler veya yerler için açık adresler gibidir. Plus Code'lar, sokak adları ve numaraları içeren adresler yerine enlem/boylam koordinatlarını temel alır ve sayı ile harf olarak gösterilir.

Google, adreslerin avantajlarından herkesin ve her şeyin yararlanabilmesi için Plus Code'ları geliştirdi. Plus Code, enlem/boylam koordinatlarından türetilen ve bir alanı temsil eden kodlanmış bir konum referansıdır: Bir derecenin 1/8.000'i x bir derecenin 1/8.000'i (ekvatorda yaklaşık 14 m x 14 m) veya daha küçük. Plus Code'ları, açık adreslerin bulunmadığı veya binaların numaralandırılmadığı ya da sokakların adlandırılmadığı yerlerde açık adres yerine kullanabilirsiniz.

Plus Code'lar, global kod veya bileşik kod olarak biçimlendirilmelidir:

  • global code, 4 karakterlik bir alan kodu ve 6 karakter veya daha uzun bir yerel koddan oluşur. Örneğin, "1600 Amphitheatre Parkway, Mountain View, CA" adresi için global kod "849V" ve yerel kod "CWC8+R9"dur. Ardından, konum değerini "849VCWC8+R9" olarak belirtmek için 10 karakterlik Plus Code'un tamamını kullanırsınız.
  • Bileşik kod, 6 karakter veya daha uzun bir yerel kod ile açık bir konumun birleşiminden oluşur. Örneğin, "450 Serra Mall, Stanford, CA 94305, ABD" adresinin yerel kodu "CRHJ+C3"tür. Bileşik adres için yerel kodu adresin şehir, eyalet, posta kodu ve ülke kısmıyla "CRHJ+C3 Stanford, CA 94305, ABD" biçiminde birleştirin.

Aşağıdaki snippet'te, Plus Code'lar kullanılarak rota başlangıç ve varış noktası için bir yol noktası belirtilerek rota hesaplama işlemi gösterilmektedir:

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