Memperlihatkan petunjuk arah dari A ke B
Artikel ini menunjukkan cara membuat permintaan rute dan menunjukkan rute di peta.
Ada dua cara untuk melakukannya. Cara pertama adalah mengkueri GET Route Directions API menggunakan TypeScript REST SDK @azure-rest/maps-route. Cara kedua adalah menggunakan Fetch API untuk membuat permintaan pencarian ke Get Route Directions API. Kedua pendekatan dijelaskan dalam artikel ini.
Mengkueri rute melalui REST SDK
import * as atlas from "azure-maps-control";
import MapsRoute, { toColonDelimitedLatLonString } from "@azure-rest/maps-route";
import "azure-maps-control/dist/atlas.min.css";
const onload = () => {
// Initialize a map instance.
const map = new atlas.Map("map", {
view: "Auto",
// Add authentication details for connecting to Azure Maps.
authOptions: {
// Use Azure Active Directory authentication.
authType: "aad",
clientId: "<Your Azure Maps Client Id>",
aadAppId: "<Your Azure Active Directory Client Id>",
aadTenant: "<Your Azure Active Directory Tenant Id>"
}
});
map.events.add("load", async () => {
// Use the access token from the map and create an object that implements the TokenCredential interface.
const credential = {
getToken: () => {
return {
token: map.authentication.getToken()
};
}
};
// Create a Route client.
const client = MapsRoute(credential, "<Your Azure Maps Client Id>");
// Create a data source and add it to the map.
const dataSource = new atlas.source.DataSource();
map.sources.add(dataSource);
// Create the GeoJSON objects which represent the start and end points of the route.
const startPoint = new atlas.data.Feature(new atlas.data.Point([-122.130137, 47.644702]), {
title: "Redmond",
icon: "pin-blue"
});
const endPoint = new atlas.data.Feature(new atlas.data.Point([-122.3352, 47.61397]), {
title: "Seattle",
icon: "pin-round-blue"
});
// Add the data to the data source.
dataSource.add([startPoint, endPoint]);
// Create a layer for rendering the route line under the road labels.
map.layers.add(
new atlas.layer.LineLayer(dataSource, null, {
strokeColor: "#2272B9",
strokeWidth: 5,
lineJoin: "round",
lineCap: "round"
}),
"labels"
);
// Create a layer for rendering the start and end points of the route as symbols.
map.layers.add(
new atlas.layer.SymbolLayer(dataSource, null, {
iconOptions: {
image: ["get", "icon"],
allowOverlap: true,
ignorePlacement: true
},
textOptions: {
textField: ["get", "title"],
offset: [0, 1.2]
},
filter: ["any", ["==", ["geometry-type"], "Point"], ["==", ["geometry-type"], "MultiPoint"]] //Only render Point or MultiPoints in this layer.
})
);
// Get the coordinates of the start and end points.
const coordinates = [
[startPoint.geometry.coordinates[1], startPoint.geometry.coordinates[0]],
[endPoint.geometry.coordinates[1], endPoint.geometry.coordinates[0]]
];
// Get the route directions between the start and end points.
const response = await client.path("/route/directions/{format}", "json").get({
queryParameters: {
query: toColonDelimitedLatLonString(coordinates)
}
});
// Get the GeoJSON feature collection of the route.
const data = getFeatures(response.body.routes);
// Add the route data to the data source.
dataSource.add(data);
// Update the map view to center over the route.
map.setCamera({
bounds: data.bbox,
padding: 40
});
});
};
/**
* Helper function to convert a route response into a GeoJSON FeatureCollection.
*/
const getFeatures = (routes) => {
const bounds = [];
const features = routes.map((route, index) => {
const multiLineCoords = route.legs.map((leg) => {
return leg.points.map((coord) => {
const position = [coord.longitude, coord.latitude];
bounds.push(position);
return position;
});
});
// Include all properties on the route object except legs.
// Legs is used to create the MultiLineString, so we only need the summaries.
// The legSummaries property replaces the legs property with just summary data.
const props = {
...route,
legSummaries: route.legs.map((leg) => leg.summary),
resultIndex: index
};
delete props.legs;
return {
type: "Feature",
geometry: {
type: "MultiLineString",
coordinates: multiLineCoords
},
properties: props
};
});
return {
type: "FeatureCollection",
features: features,
bbox: new atlas.data.BoundingBox.fromLatLngs(bounds)
};
};
document.body.onload = onload;
Dalam contoh kode sebelumnya, blok pertama membuat objek peta dan mengatur mekanisme autentikasi untuk menggunakan ID Microsoft Entra. Anda dapat melihat Membuat peta untuk instruksi.
Blok kode kedua membuat objek yang mengimplementasikan antarmuka TokenCredential untuk mengautentikasi permintaan HTTP ke Azure Peta dengan token akses. Kemudian meneruskan objek kredensial ke Peta Route dan membuat instans klien.
Blok kode ketiga membuat dan menambahkan objek DataSource ke peta.
Blok kode keempat membuat objek titik awal dan akhir dan menambahkannya ke objek dataSource.
Garis adalah Fitur untuk LineString. LineLayer merender objek garis yang dibungkus dalam DataSource sebagai garis pada peta. Blok kode keempat membuat dan menambahkan lapisan garis ke peta. Lihat properti lapisan garis di LinestringLayerOptions.
Lapisan simbol menggunakan teks atau ikon untuk merender data berbasis titik yang dibungkus dalam DataSource. Teks atau ikon dirender sebagai simbol pada peta. Blok kode kelima membuat dan menambahkan lapisan simbol ke peta.
Blok kode keenam meminta layanan perutean Azure Peta, yang merupakan bagian dari klien Peta Route. Permintaan GET digunakan untuk mendapatkan rute antara titik awal dan akhir. Kumpulan fitur GeoJSON dari respons kemudian diekstrak menggunakan getFeatures()
fungsi pembantu dan ditambahkan ke sumber data. Ini kemudian merender respons sebagai rute di peta. Untuk informasi selengkapnya tentang menambahkan garis ke peta, lihat Menambahkan baris di peta.
Blok kode terakhir menetapkan batas peta menggunakan properti setCamera Peta.
Kueri rute, sumber data, simbol, lapisan garis, dan batas kamera dibuat di dalam listener peristiwa. Struktur kode ini memastikan hasil ditampilkan hanya setelah peta dimuat sepenuhnya.
Kueri rute melalui Fetch API
import * as atlas from "azure-maps-control";
import "azure-maps-control/dist/atlas.min.css";
const onload = () => {
// Initialize a map instance.
const map = new atlas.Map("map", {
view: "Auto",
// Add authentication details for connecting to Azure Maps.
authOptions: {
// Use Azure Active Directory authentication.
authType: "aad",
clientId: "<Your Azure Maps Client Id>",
aadAppId: "<Your Azure Active Directory Client Id>",
aadTenant: "<Your Azure Active Directory Tenant Id>"
}
});
map.events.add("load", async () => {
// Create a data source and add it to the map.
const dataSource = new atlas.source.DataSource();
map.sources.add(dataSource);
// Create the GeoJSON objects which represent the start and end points of the route.
const startPoint = new atlas.data.Feature(new atlas.data.Point([-122.130137, 47.644702]), {
title: "Redmond",
icon: "pin-blue"
});
const endPoint = new atlas.data.Feature(new atlas.data.Point([-122.3352, 47.61397]), {
title: "Seattle",
icon: "pin-round-blue"
});
// Add the data to the data source.
dataSource.add([startPoint, endPoint]);
// Create a layer for rendering the route line under the road labels.
map.layers.add(
new atlas.layer.LineLayer(dataSource, null, {
strokeColor: "#2272B9",
strokeWidth: 5,
lineJoin: "round",
lineCap: "round"
}),
"labels"
);
// Create a layer for rendering the start and end points of the route as symbols.
map.layers.add(
new atlas.layer.SymbolLayer(dataSource, null, {
iconOptions: {
image: ["get", "icon"],
allowOverlap: true,
ignorePlacement: true
},
textOptions: {
textField: ["get", "title"],
offset: [0, 1.2]
},
filter: ["any", ["==", ["geometry-type"], "Point"], ["==", ["geometry-type"], "MultiPoint"]] //Only render Point or MultiPoints in this layer.
})
);
// Send a request to the route API
let url = "https://atlas.microsoft.com/route/directions/json?";
url += "&api-version=1.0";
url +=
"&query=" +
startPoint.geometry.coordinates[1] +
"," +
startPoint.geometry.coordinates[0] +
":" +
endPoint.geometry.coordinates[1] +
"," +
endPoint.geometry.coordinates[0];
// Process request
fetch(url, {
headers: {
Authorization: "Bearer " + map.authentication.getToken(),
"x-ms-client-id": "<Your Azure Maps Client Id>"
}
})
.then((response) => response.json())
.then((response) => {
const bounds = [];
const route = response.routes[0];
// Create an array to store the coordinates of each turn
let routeCoordinates = [];
route.legs.forEach((leg) => {
const legCoordinates = leg.points.map((point) => {
const position = [point.longitude, point.latitude];
bounds.push(position);
return position;
});
// Add each turn coordinate to the array
routeCoordinates = routeCoordinates.concat(legCoordinates);
});
// Add route line to the dataSource
dataSource.add(new atlas.data.Feature(new atlas.data.LineString(routeCoordinates)));
// Update the map view to center over the route.
map.setCamera({
bounds: new atlas.data.BoundingBox.fromLatLngs(bounds),
padding: 40
});
});
});
};
document.body.onload = onload;
Dalam contoh kode sebelumnya, blok kode pertama membuat objek peta dan mengatur mekanisme autentikasi untuk menggunakan ID Microsoft Entra. Anda dapat melihat Membuat peta untuk instruksi.
Blok kode kedua membuat dan menambahkan objek DataSource ke peta.
Blok kode ketiga membuat titik awal dan tujuan untuk rute. Kemudian, ini menambahkannya ke sumber data. Untuk informasi selengkapnya, lihat Menambahkan pin di peta.
LineLayer merender objek garis yang dibungkus dalam DataSource sebagai garis pada peta. Blok kode keempat membuat dan menambahkan lapisan garis ke peta. Lihat properti lapisan garis di LineLayerOptions.
Lapisan simbol menggunakan teks atau ikon untuk merender data berbasis titik yang dibungkus dalam DataSource sebagai simbol di peta. Blok kode kelima membuat dan menambahkan lapisan simbol ke peta. Lihat properti lapisan simbol di SymbolLayerOptions.
Blok kode berikutnya menggunakan Fetch API untuk membuat permintaan pencarian ke Dapatkan Petunjuk Arah Rute. Responnya kemudian diuraikan. Jika respons berhasil, informasi garis lintang dan garis bujur digunakan untuk membuat array garis dengan menghubungkan titik-titik tersebut. Data garis kemudian ditambahkan ke sumber data untuk membuat rute pada peta. Untuk informasi selengkapnya, lihat Menambahkan baris di peta.
Blok kode terakhir menetapkan batas peta menggunakan properti setCamera Peta.
Kueri rute, sumber data, simbol, lapisan garis, dan batas kamera dibuat di dalam listener peristiwa. Sekali lagi, kita ingin memastikan bahwa hasil ditampilkan setelah peta dimuat sepenuhnya.
Gambar berikut adalah cuplikan layar yang menunjukkan hasil dari dua sampel kode.
Langkah berikutnya
Pelajari selengkapnya tentang kelas dan metode yang digunakan di artikel ini:
Lihat artikel berikut untuk contoh kode lengkap: