รับเส้นทาง

นักพัฒนาแอปในเขตเศรษฐกิจยุโรป (EEA)

เส้นทางคือเส้นทางที่นำทางได้ระหว่างตำแหน่งเริ่มต้นหรือต้นทางกับตำแหน่งสิ้นสุดหรือจุดหมาย คุณเลือกรับเส้นทางสำหรับรูปแบบการ เดินทางต่างๆ ได้ เช่น การเดิน การปั่นจักรยาน หรือยานพาหนะประเภทต่างๆ นอกจากนี้ คุณยัง ขอรายละเอียดเส้นทาง เช่น ระยะทาง เวลาโดยประมาณในการนำทางตาม เส้นทาง ค่าผ่านทางที่คาดไว้ และวิธีการแบบทีละขั้นตอนในการนำทางตามเส้นทางได้ด้วย

ดูซอร์สโค้ดตัวอย่างที่สมบูรณ์

ตัวอย่างโค้ดต่อไปนี้แสดงวิธีรับเส้นทางสำหรับการขับรถระหว่างสถานที่ 2 แห่ง

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>

ลองใช้ตัวอย่าง

เรียกใช้เมธอด computeRoutes() เพื่อขอเส้นทางระหว่าง 2 สถานที่ ตัวอย่างต่อไปนี้แสดงการกำหนดคำขอ และเรียกใช้ computeRoutes() เพื่อรับเส้นทาง

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

เลือกช่องที่จะแสดง

เมื่อขอเส้นทาง คุณต้องใช้มาสก์ฟิลด์เพื่อระบุข้อมูลที่การตอบกลับควรแสดง คุณระบุชื่อของ พร็อพเพอร์ตี้คลาสเส้นทาง ในฟิลด์มาสก์ได้

การใช้ Field Mask ยังช่วยให้มั่นใจได้ว่าคุณจะไม่ขอข้อมูลที่ไม่จำเป็น ซึ่งจะช่วยลดเวลาในการตอบสนองและหลีกเลี่ยงการแสดงข้อมูลที่ระบบของคุณไม่ต้องการ

ระบุรายการฟิลด์ที่ต้องการโดยตั้งค่าพร็อพเพอร์ตี้ ComputeRoutesRequest.fields ดังที่แสดงในข้อมูลโค้ดต่อไปนี้

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

ระบุสถานที่สำหรับเส้นทาง

หากต้องการคำนวณเส้นทาง คุณต้องระบุตำแหน่งต้นทางและปลายทางของเส้นทาง รวมถึงมาสก์ฟิลด์เป็นอย่างน้อย นอกจากนี้ คุณยังระบุจุดแวะพักกลางทางตามเส้นทาง และใช้จุดแวะพักเพื่อทำสิ่งอื่นๆ เช่น เพิ่มจุดแวะพักหรือจุดส่งต่อตามเส้นทางได้ด้วย

ในComputeRoutesRequest คุณระบุสถานที่ตั้งได้ด้วยวิธีใดวิธีหนึ่งต่อไปนี้

คุณสามารถระบุสถานที่สำหรับจุดแวะพักทั้งหมดในคำขอด้วยวิธีเดียวกัน หรือจะผสมกันก็ได้ เช่น คุณสามารถใช้พิกัดละติจูด/ลองจิจูดสำหรับจุดพักต้นทาง และใช้วัตถุสถานที่สำหรับจุดพักปลายทาง

ใช้ออบเจ็กต์สถานที่แทนพิกัดละติจูด/ลองจิจูดหรือสตริงที่อยู่เพื่อให้มีประสิทธิภาพและความแม่นยำ รหัสสถานที่เป็นรหัสที่ไม่ซ้ำกันและให้ประโยชน์ในการแปลงรหัสพิกัดภูมิศาสตร์สำหรับการกำหนดเส้นทาง เช่น จุดเข้าถึงและตัวแปรการจราจร ซึ่งจะช่วยหลีกเลี่ยงสถานการณ์ต่อไปนี้ที่อาจเกิดขึ้นจากวิธีอื่นๆ ในการระบุตำแหน่ง

  • การใช้พิกัดละติจูด/ลองจิจูดอาจทำให้ระบบปักหมุดตำแหน่งบนถนน ที่ใกล้กับพิกัดเหล่านั้นมากที่สุด ซึ่งอาจไม่ใช่จุดเข้าถึงที่พัก หรือแม้แต่ ถนนที่นำไปสู่จุดหมายได้อย่างรวดเร็วหรือปลอดภัย
  • สตริงที่อยู่ต้องได้รับการเข้ารหัสภูมิศาสตร์โดย Routes API ก่อนเพื่อแปลงเป็น พิกัดละติจูด/ลองจิจูดก่อนจึงจะคำนวณเส้นทางได้ ซึ่งอาจส่งผลต่อ ประสิทธิภาพ

ระบุสถานที่ตั้งเป็นออบเจ็กต์ 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 = {
  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.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'],
};

สตริงที่อยู่

สตริงที่อยู่คือที่อยู่ที่แท้จริงซึ่งแสดงด้วยสตริง (เช่น "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 อาจใช้พิกัดละติจูด/ลองจิจูดที่เข้ารหัสพิกัดภูมิศาสตร์ไม่ถูกต้อง ตัวอย่างเช่น คุณส่งคำขอที่ระบุ "Toledo" เป็นต้นทางและ "Madrid" เป็นปลายทางสำหรับเส้นทางการขับขี่

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

ในตัวอย่างนี้ ระบบจะตีความ "Toledo" เป็นเมืองในรัฐโอไฮโอของสหรัฐอเมริกา ไม่ใช่ในสเปน ดังนั้น คำขอจะแสดงผลอาร์เรย์ว่าง ซึ่งหมายความว่าไม่มีเส้นทาง

คุณกำหนดค่า API ให้แสดงผลลัพธ์ที่เอนเอียงไปยังภูมิภาคใดภูมิภาคหนึ่งได้โดยใส่พารามิเตอร์ regionCode พารามิเตอร์นี้จะระบุรหัสภูมิภาคเป็นค่า 2 อักขระของ 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 Codes เป็นเหมือนที่อยู่ของผู้คนหรือสถานที่ซึ่งไม่มีที่อยู่อย่างเป็นทางการ Plus Codes ไม่ใช่ข้อมูลที่อยู่ที่ประกอบด้วยชื่อถนนและบ้านเลขที่ แต่จะเป็นชุดตัวเลขและตัวอักษรที่สร้างขึ้นโดยอิงจากพิกัดละติจูด/ลองจิจูด

Google พัฒนา Plus Codes เพื่อให้ทุกคนและทุกสิ่งได้รับประโยชน์จากที่อยู่ โค้ด Plus คือการอ้างอิงตำแหน่งที่เข้ารหัส ซึ่งได้มาจากพิกัดละติจูด/ลองจิจูดที่แสดงถึงพื้นที่ขนาด 1/8000 ขององศา x 1/8000 ขององศา (ประมาณ 14 ม. x 14 ม. ที่เส้นศูนย์สูตร) หรือเล็กกว่า คุณ สามารถใช้ Plus Codes แทนที่อยู่ได้ในสถานที่ที่ไม่มีที่อยู่ หรือ ในกรณีที่ไม่มีการระบุหมายเลขอ้างอิงอาคารหรือไม่มีการตั้งชื่อถนน

Plus Codes ต้องจัดรูปแบบเป็นรหัสสากลหรือรหัสผสม ดังนี้

  • รหัสสากลประกอบด้วยรหัสพื้นที่ 4 อักขระและรหัสท้องถิ่น 6 อักขระหรือยาวกว่า นั้น ตัวอย่างเช่น สำหรับที่อยู่ "1600 Amphitheatre Parkway, Mountain View, CA" รหัสสากลคือ "849V" และรหัสท้องถิ่นคือ "CWC8+R9" จากนั้นใช้โค้ด Plus ทั้ง 10 อักขระ เพื่อระบุค่าสถานที่ตั้งเป็น "849VCWC8+R9"
  • รหัสผสมประกอบด้วยรหัสท้องถิ่นที่มีอักขระ 6 ตัวขึ้นไปรวมกับ สถานที่ตั้งที่ชัดเจน เช่น ที่อยู่ "450 Serra Mall, Stanford, CA 94305, USA" มี รหัสท้องถิ่น "CRHJ+C3" สำหรับที่อยู่ที่ซับซ้อน ให้รวมรหัสท้องถิ่นกับส่วนเมือง รัฐ รหัสไปรษณีย์ และประเทศของที่อยู่ในรูปแบบ "CRHJ+C3 Stanford, CA 94305, USA"

ข้อมูลโค้ดต่อไปนี้แสดงการคำนวณเส้นทางโดยการระบุจุดแวะพักสำหรับต้นทางของเส้นทาง และปลายทางโดยใช้ Plus Codes

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