你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
GitHub Copilot 是 AI 提供支持的代码助手,可帮助你更快地编写更好的代码。 GitHub Copilot 可以根据提示生成代码片段,并为现有代码建议代码补全。 GitHub Copilot 还可以从代码和首选项中学习,并适应你的风格和需求。 虽然 GitHub Copilot 无法将代码从必应地图 Web SDK 直接转换为 Azure Maps Web SDK 或从必应地图 API 转换为 Azure Maps API,但本作指南文章介绍如何使用 GitHub Copilot 为 Azure Maps 应用程序生成代码。 如果要从必应地图企业版迁移到 Azure Maps,这尤其有用。
先决条件
- 一个 Azure 帐户
- Azure Maps 帐户
- 订阅密钥或其他形式的 Azure Maps 身份验证
- 对Azure Maps Web SDK的基本了解
- 对 Azure Maps API 有基本的了解
- GitHub 帐户和 GitHub Copilot 订阅
- 请参阅以下文章以基本了解适用于企业的必应地图与 Azure Maps 之间的差异。
提示 1:用明确的句子编写提示
使用 GitHub Copilot 的第一步是用简单的句子编写提示。 提示是对代码要执行或实现的操作的简短说明。 例如,如果要使用 Azure Maps Web SDK 显示 GeoJSON 文件,可以编写如下所示的提示:
使用以下 URL 编写使用 Azure Maps WebSDK v3 在 SymbolLayer 中显示 GeoJSON 功能的 HTML 程序: https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson
然后,GitHub Copilot 使用所选语言和框架生成与提示匹配的代码片段。 例如,如果使用 HTML 和 JavaScript,GitHub Copilot 可能会生成如下所示的代码片段:
<!DOCTYPE html>
<html>
<head>
<title>Earthquake Data</title>
<script src='https://atlas.microsoft.com/sdk/javascript/mapcontrol/3/atlas.min.js'></script>
<link rel="stylesheet" href="https://atlas.microsoft.com/sdk/javascript/mapcontrol/3/atlas.min.css" type="text/css" />
<style>
#myMap { width: 100%; height: 500px; }
</style>
</head>
<body>
<div id="myMap"></div>
<script>
var map = new atlas.Map("myMap", {
center: [-100, 39],
zoom: 3,
authOptions: {
authType: 'subscriptionKey',
subscriptionKey: 'Your Azure Maps Key'
}
});
map.events.add('ready', function() {
fetch('https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson')
.then(response => response.json())
.then(data => {
var dataSource = new atlas.source.DataSource();
map.sources.add(dataSource);
dataSource.add(data);
map.layers.add(new atlas.layer.SymbolLayer(dataSource));
});
});
</script>
</body>
</html>
如你所看到的,GitHub Copilot 可以从简单明了的提示生成完整的功能代码片段。 然后,可以将代码片段复制并粘贴到代码编辑器中,或根据需要对其进行修改。 还可以要求 GitHub Copilot 生成替代代码片段,或者完成或建议对现有代码进行更改。
在明确的句子中编写提示,而不是依赖必应地图企业版应用程序中的代码片段的优势在于,你可以专注于应用程序的逻辑和功能,从而使 GitHub Copilot 更准确地了解目标。 还可以避免复制和粘贴可能模棱两可且可能会混淆 GitHub Copilot 的代码片段。
注释
每次运行同一提示时,可能会获得不同的结果,有时可能会遇到不准确情况,例如不存在的方法。 请确保检查浏览器控制台是否存在任何错误,并根据需要调整代码。
提示 2:提供详细的分步说明
使用 GitHub Copilot 的第二个提示是提供详细的分步说明。 假设你是一位为产品编写功能规范的产品经理。 例如,如果要对地址“1 Microsoft Way、Redmond、WA”进行地理编码,并在地图上添加标记,可以编写如下所示的提示:
使用 Azure Maps Web SDK v3 编写 HTML 程序,为“1 Microsoft Way、Redmond、WA”坐标发出地理编码请求,然后将标记放置在该位置。步骤 1. 利用地理编码 API 终结点:
<https://atlas.microsoft.com/geocode?api-version=2023-06-01&subscription-key=${subscriptionKey}&query=${query}>。 提供了一个示例响应供参考。{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"address":{"countryRegion":{"name":"United States"},"adminDistricts":[{"shortName":"WA"},{"shortName":"King County"}],"formattedAddress":"15127 NE 24th St, Redmond, WA 98052","locality":"Redmond","postalCode":"98052","addressLine":"15127 NE 24th St"},"type":"Address","confidence":"High","matchCodes":["Good"],"geocodePoints":[{"geometry":{"type":"Point","coordinates":[-122.138681,47.630358]},"calculationMethod":"Rooftop","usageTypes":["Display"]},{"geometry":{"type":"Point","coordinates":[-122.1386787,47.6302179]},"calculationMethod":"Rooftop","usageTypes":["Route"]}]},"geometry":{"type":"Point","coordinates":[-122.138681,47.630358]},"bbox":[-122.14632282407,47.626495282429325,-122.13103917593001,47.63422071757068]}]}
步骤 2. 为“1 Microsoft Way,Redmond, WA”的坐标发出地理编码 API 请求。
步骤 3. 使用 Azure Maps WebSDK 显示地图,将其居中位于从地理编码 API 响应获取的坐标上。
步骤 4. 等待地图资源准备就绪。
步骤 5. 将标记放置在从 API 响应获取的坐标上。
GitHub Copilot 使用 Azure Maps 地理编码 API 和 Azure Maps Web SDK 生成与说明匹配的代码片段。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Azure Maps Geocode and Pushpin Example</title>
<link href="https://atlas.microsoft.com/sdk/javascript/mapcontrol/3/atlas.min.css" rel="stylesheet" />
<script src="https://atlas.microsoft.com/sdk/javascript/mapcontrol/3/atlas.min.js"></script>
<style>
#map {
width: 100%;
height: 400px;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var subscriptionKey = 'YOUR_SUBSCRIPTION_KEY'; // Replace with your Azure Maps subscription key
var query = '1 Microsoft Way, Redmond';
// Make Geocode API request
fetch(`https://atlas.microsoft.com/geocode?api-version=2023-06-01&subscription-key=${subscriptionKey}&query=${query}`)
.then(response => response.json())
.then(data => {
// Extract coordinates from the API response
var coordinates = data.features[0].geometry.coordinates;
// Initialize map
var map = new atlas.Map('map', {
center: coordinates,
zoom: 14,
view: 'Auto',
authOptions: {
authType: 'subscriptionKey',
subscriptionKey: subscriptionKey
}
});
// Wait until map resources are ready
map.events.add('ready', function () {
// Add pushpin to the map
var pushpin = new atlas.HtmlMarker({
position: coordinates,
htmlContent: '<div style="background-color: #286090; color: #fff; padding: 5px;">1 Microsoft Way</div>'
});
map.markers.add(pushpin);
});
})
.catch(error => console.error('Error:', error));
</script>
</body>
</html>
将复杂的提示分解为各个步骤使 GitHub Copilot 更容易理解和遵循,从而更好地控制代码流。
注释
若要创建有效的提示,需要针对不同的方案自定义它们。 通过迭代优化提示,可以实现最佳结果。
提示 3:包括 API 请求输入和输出的示例
使用 GitHub Copilot 的第三个提示是包含 API 输入和输出的示例。 提供示例可以改进 Copilot 生成准确和相关代码片段的能力,方法是允许它了解如何处理数据。
若要获取 Azure Maps API 的输入和输出示例,请参阅 Azure Maps REST API 文档。 例如,可以查看 Azure Maps Geocoding Batch API 和 Azure Maps Directions API 的示例请求正文和响应。 如果要使用 Azure Maps 创建应用程序以在两个位置之间路由,可以编写如下所示的提示:
使用 Azure Maps Web SDK v3 实现 HTML 程序,以显示用户指定位置的路线方向。步骤 1. 创建两个输入框,供用户输入起始和结束街道地址。 添加提交按钮以继续执行下一步。
步骤 2. 利用地理编码批量POST接口:https://atlas.microsoft.com/geocode:batch?api-version=2023-06-01&subscription-key=${subscriptionKey}以查找起点和终点的坐标。
示例请求正文:
{ "batchItems": [ { "addressLine": "1 Microsoft Way, Redmond, WA" }, { "addressLine": "400 Broad St, Seattle, WA" } ] }
示例响应:
{"batchItems":[{"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Point","coordinates":[-122.128265,47.639385]},"bbox":[-122.13590814413995,47.63552228242932,-122.12062185586005,47.643247717570674],"properties":{"type":"Address","confidence":"Medium","matchCodes":["Good"],"geocodePoints":[{"calculationMethod":"Rooftop","usageTypes":["Display"],"geometry":{"type":"Point","coordinates":[-122.128265,47.639385]}},{"calculationMethod":"Rooftop","usageTypes":["Route"],"geometry":{"type":"Point","coordinates":[-122.1271239,47.6385519]}}],"address":{"addressLine":"1 Microsoft Way","postalCode":"98052","locality":"Redmond","formattedAddress":"1 Microsoft Way, Redmond, WA 98052","countryRegion":{"name":"United States","ISO":"US"},"adminDistricts":[{"shortName":"WA"},{"shortName":"King County"}]}}}]},{"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Point","coordinates":[-122.349309,47.620498]},"bbox":[-122.35694938292329,47.61663528242932,-122.34166861707672,47.624360717570674],"properties":{"type":"Address","confidence":"High","matchCodes":["Good"],"geocodePoints":[{"calculationMethod":"Rooftop","usageTypes":["Display"],"geometry":{"type":"Point","coordinates":[-122.349309,47.620498]}},{"calculationMethod":"Rooftop","usageTypes":["Route"],"geometry":{"type":"Point","coordinates":[-122.3485587,47.6200534]}}],"address":{"addressLine":"400 Broad St","postalCode":"98109","neighborhood":"Queen Anne","locality":"Seattle","formattedAddress":"400 Broad St, Seattle, WA 98109","countryRegion":{"name":"United States","ISO":"US"},"adminDistricts":[{"shortName":"WA"},{"shortName":"King County"}]}}}]}],"summary":{"successfulRequests":2,"totalRequests":2}}
步骤 3. 使用 Azure Maps WebSDK 显示地图。
步骤 4. 等待地图资源准备就绪。
步骤 5. 创建 DataSource 并将其添加到地图。
步骤 6. 创建 SymbolLayer 并将其添加到地图。
步骤 7. 创建 LineLayer 并将其添加到地图。
步骤 8。 利用路由 POST API:
https://atlas.microsoft.com/route/directions?api-version=2025-01-01&subscription-key=${subscriptionKey}以查找起点和终点之间的路由。 将 GeoJSON 响应添加到 DataSource,并根据响应的边界框调整地图的相机。示例请求正文:
{ "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": { "coordinates": [ -122.1271239, 47.6385519 ], "type": "Point" }, "properties": { "pointIndex": 0, "pointType": "waypoint" } }, { "type": "Feature", "geometry": { "coordinates": [ -122.3485587, 47.6200534 ], "type": "Point" }, "properties": { "pointIndex": 1, "pointType": "waypoint" } } ], "routeOutputOptions": [ "routePath" ],
"travelMode": "driving" }
示例响应:
{"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Point","coordinates":[-122.127124,47.638552]},"properties":{"routePathPoint":{"legIndex":0,"pointIndex":0},"order":{"inputIndex":0},"type":"Waypoint"}},{"type":"Feature","geometry":{"type":"Point","coordinates":[-122.348533,47.620073]},"properties":{"routePathPoint":{"legIndex":0,"pointIndex":113},"order":{"inputIndex":1},"type":"Waypoint"}},{"type":"Feature","geometry":{"type":"MultiLineString","coordinates":[[[-122.127123,47.638551],[-122.127236,47.638786],[-122.127778,47.639321],[-122.127588,47.639453],[-122.126935,47.639906],[-122.128569,47.64092],[-122.128269,47.641159],[-122.128004,47.641435],[-122.128064,47.641947],[-122.127464,47.642446],[-122.127433,47.642452],[-122.127358,47.642589],[-122.127333,47.642706],[-122.127044,47.643317],[-122.127,47.646063],[-122.12707,47.646064],[-122.1355,47.646072],[-122.135465,47.645943],[-122.134932,47.644569],[-122.134655,47.643384],[-122.134688,47.64219],[-122.134994,47.640816],[-122.135396,47.640114],[-122.135694,47.639576],[-122.136586,47.638589],[-122.138502,47.637193],[-122.14906,47.631126],[-122.150578,47.630481],[-122.152672,47.629904],[-122.15453,47.629628],[-122.156691,47.629525],[-122.163925,47.630213],[-122.168574,47.629931],[-122.170237,47.629981],[-122.171667,47.630214],[-122.179348,47.631954],[-122.181849,47.632144],[-122.185924,47.632041],[-122.186778,47.632117],[-122.187833,47.632345],[-122.188876,47.632739],[-122.190017,47.633476],[-122.190692,47.634194],[-122.191623,47.635672],[-122.192652,47.636933],[-122.195835,47.639784],[-122.197456,47.640891],[-122.199124,47.641725],[-122.20114,47.642394],[-122.202483,47.642648],[-122.206548,47.643149],[-122.208346,47.643164],[-122.210355,47.642861],[-122.218068,47.640503],[-122.219353,47.64005],[-122.220547,47.639476],[-122.223398,47.637523],[-122.224491,47.636915],[-122.22566,47.636477],[-122.226843,47.636165],[-122.228471,47.635972],[-122.229575,47.636001],[-122.231286,47.636192],[-122.238445,47.637468],[-122.241606,47.638218],[-122.243095,47.638484],[-122.269838,47.642514],[-122.275227,47.643424],[-122.279804,47.644349],[-122.282342,47.644655],[-122.289531,47.645049],[-122.29387,47.645413],[-122.296978,47.645393],[-122.300182,47.645129],[-122.304222,47.64444],[-122.308205,47.64353],[-122.30968,47.64328],[-122.31467,47.643113],[-122.318608,47.64274],[-122.318874,47.642714],[-122.321852,47.642389],[-122.322434,47.642195],[-122.322857,47.641863],[-122.323024,47.641566],[-122.323072,47.641284],[-122.323134,47.638686],[-122.323246,47.637911],[-122.323243,47.637778],[-122.323332,47.636353],[-122.323548,47.635195],[-122.323781,47.634413],[-122.324407,47.632851],[-122.324663,47.632356],[-122.3252,47.631657],[-122.326806,47.630159],[-122.327268,47.629875],[-122.327954,47.629266],[-122.328755,47.628281],[-122.328928,47.627756],[-122.328967,47.626499],[-122.329233,47.626199],[-122.330614,47.625588],[-122.332592,47.625034],[-122.334379,47.624774],[-122.334564,47.624765],[-122.336411,47.624697],[-122.340045,47.624729],[-122.342033,47.624546],[-122.343379,47.624517],[-122.347561,47.624571],[-122.347564,47.624483],[-122.347606,47.62079],[-122.347687,47.620726],[-122.348533,47.620073]]],"bbox":[-122.348533,47.620073,-122.126935,47.646072]},"properties":{"resourceId":"v70,h-1356265451,i0,a0,cen-US,dAAAAAAAAAAA1,y0,s1,m1,o1,t0,wO6aTEbzRR0CPQkjMIohewA2
v12,k1,qatt:1","trafficCongestion":"None","trafficDataUsed":"None","distanceInMeters":21606,"durationInSeconds":1455,"departureTime":"2024-03-04T03:05:01+00:00","arrivalTime":"2024-03-04T03:29:16+00:00","type":"RoutePath","legs":[{"distanceInMeters":21606,"durationInSeconds":1455,"departureTime":"2024-03-04T03:05:01+00:00","arrivalTime":"2024-03-04T03:29:16+00:00","routePathRange":{"legIndex":0,"range":[0,113]},"description":"WA-520 W"}]}}]}v12,wBmPp6F3PR0AfTybJTpZewA2
GitHub Copilot 可以创建以下代码片段,为用户提供一个界面,以便用户输入开始和结束地址,并使用 Azure Maps API 基于示例输入和输出在地图上显示路线。
<!DOCTYPE html>
<html>
<head>
<title>Azure Maps Route Directions</title>
<meta charset="utf-8" />
<link
href="https://atlas.microsoft.com/sdk/javascript/mapcontrol/3/atlas.min.css"
rel="stylesheet"
/>
<script src="https://atlas.microsoft.com/sdk/javascript/mapcontrol/3/atlas.min.js"></script>
<style>
html,
body,
#myMap {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
}
#inputPanel {
position: absolute;
top: 10px;
left: 10px;
z-index: 1;
background-color: rgba(255, 255, 255, 0.7);
padding: 10px;
border-radius: 10px;
}
</style>
</head>
<body>
<div id="inputPanel">
<input id="startInput" placeholder="Enter starting address" />
<input id="endInput" placeholder="Enter ending address" />
<button id="submitBtn">Get Directions</button>
</div>
<div id="myMap"></div>
<script>
var subscriptionKey = "YOUR_SUBSCRIPTION_KEY";
var map, dataSource;
function getCoordinates() {
var startAddress = document.getElementById("startInput").value;
var endAddress = document.getElementById("endInput").value;
fetch(
`https://atlas.microsoft.com/geocode:batch?api-version=2023-06-01&subscription-key=${subscriptionKey}`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
batchItems: [
{
addressLine: startAddress,
},
{
addressLine: endAddress,
},
],
}),
}
)
.then((response) => response.json())
.then((data) => {
var startCoordinates =
data.batchItems[0].features[0].geometry.coordinates;
var endCoordinates =
data.batchItems[1].features[0].geometry.coordinates;
getRoute(startCoordinates, endCoordinates);
});
}
function getRoute(startCoordinates, endCoordinates) {
fetch(
`https://atlas.microsoft.com/route/directions?api-version=2025-01-01&subscription-key=${subscriptionKey}`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
type: "FeatureCollection",
features: [
{
type: "Feature",
geometry: {
coordinates: startCoordinates,
type: "Point",
},
properties: {
pointIndex: 0,
pointType: "waypoint",
},
},
{
type: "Feature",
geometry: {
coordinates: endCoordinates,
type: "Point",
},
properties: {
pointIndex: 1,
pointType: "waypoint",
},
},
],
routeOutputOptions: ["routePath"],
travelMode: "driving",
}),
}
)
.then((response) => response.json())
.then((data) => {
dataSource.clear();
dataSource.add(data);
map.setCamera({
bounds: atlas.data.BoundingBox.fromData(data),
padding: 50,
});
});
}
map = new atlas.Map("myMap", {
authOptions: {
authType: "subscriptionKey",
subscriptionKey: subscriptionKey,
},
});
map.events.add("ready", function () {
dataSource = new atlas.source.DataSource();
map.sources.add(dataSource);
map.layers.add(new atlas.layer.LineLayer(dataSource));
map.layers.add(new atlas.layer.SymbolLayer(dataSource));
document
.getElementById("submitBtn")
.addEventListener("click", getCoordinates);
});
</script>
</body>
</html>
提供 Azure Maps API 请求输入和响应输出的示例可帮助 GitHub Copilot 生成更准确且相关的代码片段。 缩小 JSON 以在必要时减少令牌计数。 调用自己的 API 服务时,还可以应用相同的技术,从而允许 GitHub Copilot 了解 API 的工作原理。
已知的限制
请记住,生成的代码片段需要工程工作才能查看,并且存在一些限制:
- 除非显式指示 GitHub Copilot 添加 CSS 样式,否则通常不包括 CSS 样式。
- 如果要求 Copilot 将必应地图 Web SDK 代码转换为 Azure Maps Web SDK 代码,通常会产生错误结果,因为它们之间并不总是一对一映射。
- 你可能会遇到偶尔出现不准确的情况,这需要调试技能和反复试错的过程。
结论
本作指南演示如何使用 GitHub Copilot 为应用程序生成代码片段。 将应用程序从 Bing Maps for Enterprise 迁移到 Azure Maps 时,此功能非常有用。
我们已介绍以下内容:
- 用明确的句子编写提示。
- 提供详细的分步说明。
- 包括 Azure Maps API 请求输入和响应输出的示例。
后续步骤
探索其他高级提示工程技术,以帮助你优化提示。