共用方式為


使用 GitHub Copilot 將 Bing 地圖 Enterprise 應用程式遷移至 Azure 地圖服務

GitHub Copilot 是 AI 型程式代碼助理,可協助您更快撰寫更好的程式碼。 GitHub Copilot 可以從提示產生代碼段,並建議現有程式代碼完成。 GitHub Copilot 也可以從您的程式代碼和喜好設定中學習,並適應您的樣式和需求。 雖然 GitHub Copilot 無法將程式代碼從 Bing 地圖 Web SDK 直接轉換成 Azure 地圖服務 Web SDK,或從 Bing 地圖 API 轉換為 Azure 地圖服務 API,但本操作說明文章說明如何使用 GitHub Copilot 來產生 Azure 地圖服務 應用程式的程式代碼。 如果您要從 Bing 地圖 for Enterprise 移轉至 Azure 地圖服務,這特別有用。

必要條件

秘訣 1:以清楚的句子撰寫提示

使用 GitHub Copilot 的第一個步驟是以簡單的句子撰寫提示。 提示是您想要使用程式代碼執行或達成之動作的簡短描述。 例如,如果您想要使用 Azure 地圖服務 Web SDK 顯示 GeoJSON 檔案,您可能會撰寫如下的提示:

使用 Azure 地圖服務 WebSDK v3 撰寫 HTML 程式,以從下列 URL 在 SymbolLayer 中顯示 GeoJSON 功能: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>

Azure 地圖服務 的螢幕快照,其中顯示地震位置有藍色圖釘的 北美洲。

如您所見,GitHub Copilot 可以從簡單且清楚的提示產生完整的功能代碼段。 然後,您可以將代碼段複製並貼到程式碼編輯器中,或視需要加以修改。 您也可以要求 GitHub Copilot 產生替代代碼段,或完成或建議現有程式代碼的變更。

在清楚的句子中撰寫提示,而不是依賴 Bing 地圖 企業版應用程式的代碼段,的優點在於您可以專注於應用程式的邏輯和功能,讓 GitHub Copilot 更精確地瞭解您的目標。 您也可以避免複製和貼上可能模棱兩可且可能會混淆 GitHub Copilot 的代碼段。

注意

每次執行相同的提示時,您可能會收到不同的結果,而且偶爾可能會遇到錯誤,例如不存在的方法。 請務必檢查瀏覽器主控台是否有任何錯誤,並視需要調整程式代碼。

秘訣 2:提供詳細的逐步指示

使用 GitHub Copilot 的第二個秘訣是提供詳細的逐步指示。 假設您是為產品撰寫功能規格的產品經理。 例如,如果您想要將位址 '1 Microsoft Way、Redmond、WA' 地理編碼,並在地圖上新增標記,您可以撰寫如下的提示:

使用 Azure 地圖服務 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”:“美國”},“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“:”屋頂“,”usageTypes“:[”Display“]},{”geometry“:{”type“:”Point“,”coordinates“:[-122.1386787,47.6302179]},”calculationMethod“:”屋頂“,”usageTypes“:[”Route“]}]},”geometry“:{”type“:”Point“,”coordinates“:[-122.138681,47.630358]},”bbox“:[-122.1463282407,47.626495282429325,-122.13103917593001,47.634222071757068]}]}

步驟 2。 對 『1 Microsoft Way, Redmond, WA』 座標提出地理編碼 API 要求。

步驟 3: 使用 Azure 地圖服務 WebSDK 來顯示地圖,並將地圖置中於從 Geocode API 回應取得的座標上。

步驟 4. 等到地圖資源就緒為止。

步驟 5: 將標記放在從 API 回應取得的座標上。

GitHub Copilot 會使用 Azure 地圖服務 Geocode APIAzure 地圖服務 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>

顯示先前程式代碼範例結果的螢幕快照,此地圖是 Redmond Washington 的地圖,其圖釘標示為 1 Microsoft Way。

將複雜的提示分解成個別步驟,可讓您更輕鬆地瞭解並遵循 GitHub Copilot,讓您更妥善地控制程式碼流程。

注意

若要建立有效的提示,您必須針對不同的案例自定義它們。 反覆調整提示可讓您達到最佳可能的結果。

秘訣 3:包含 API 要求輸入和響應輸出的範例

使用 GitHub Copilot 的第三個秘訣是包含 API 輸入和輸出的範例。 提供範例可藉由讓 Copilot 瞭解如何處理數據,來改善 Copilot 產生精確且相關的代碼段的能力。

若要取得 Azure 地圖服務 API 的輸入和輸出範例,您可以參閱 Azure 地圖服務 REST API 檔。 例如,您可以看到 Azure 地圖服務 Geocoding Batch API 和 Azure 地圖服務 Directions API 的範例要求本文和回應。 如果您想要使用 Azure 地圖服務 建立應用程式以在兩個位置之間路由,您可以撰寫如下的提示:

使用 Azure 地圖服務 Web SDK v3 實作 HTML 程式,以顯示使用者指定位置的路線指示。

步驟 1: 建立兩個輸入方塊,讓使用者輸入開始和結束的街道位址。 新增提交按鈕以繼續進行下一個步驟。

步驟 2。 利用地理編碼 Batch POST API: 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.12062185 586005,47.643247717570674],“properties”:{“type”:“Address”,“confidence”:“Medium”,“matchCodes”:[“Good”],“geocodePoints”:[{“calculationMethod”:“屋頂”,“usageTypes”:[“Display”],“geometry”:{“type”:“Point”,“坐標”:[-122.128265,47.639385]}},{”calculationMethod“:”屋頂“,”usageTypes“:[”Route“],”geometry“:{”type“:”Point“,”coordinates“:[-122.1271239,47.63855 19]}}],”address“:{”addressLine“:”1 Microsoft Way“,”postalCode“:”98052“,”locality“:”Redmond“,”formattedAddress“:”1 Microsoft Way, Redmond, WA 98052“,”countryRegion“:{”name“:”美國“,”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“:”屋頂“,”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“:”美國“,”ISO“:”US“},”adminDistricts“:[{”shortName“:”WA“},{”shortName“:”King County“}]}],”summary“:{”successRequests“:2,”totalRequests“:2}}

步驟 3: 使用 Azure 地圖服務 WebSDK 來顯示地圖。

步驟 4. 等到地圖資源就緒為止。

步驟 5: 建立 DataSource 並新增至對應。

步驟 6。 建立 SymbolLayer 並新增至地圖。

步驟 7。 建立LineLayer並新增至地圖。

步驟 8。 利用路由 POST API: https://atlas.microsoft.com/route/directions?api-version=2023-10-01-preview&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.63855 2]},“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.347687,47.620726],[-1 122.348533,47.620073]],“bbox”:[-122.348533,47.620073,-122.126935,47.646072]},“properties”:{“resourceId”:“v70,h-1356265451,i0,a0,cen-US,dAAAAAAAAAAAAAAAAA1,y0,s1,m1,o1,t0,wO6aTEbzRR0CPQkjMIohewA2v12,wBmPp6F3PR0AfTybJTpZewA2v12,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”}]}}]}

GitHub Copilot 可以建立下列代碼段,以提供介面讓使用者輸入開始和結束位址,並根據範例輸入和輸出,在地圖上顯示路由 Azure 地圖服務 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=2023-10-01-preview&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 地圖服務 地圖螢幕快照。

提供 Azure 地圖服務 API 要求輸入和響應輸出的範例,可協助 GitHub Copilot 產生更精確且相關的代碼段。 視需要縮小 JSON 以減少令牌計數。 呼叫您自己的 API 服務時,也可以套用相同的技術,讓 GitHub Copilot 瞭解 API 的運作方式。

已知的限制

請記住,產生的代碼段需要工程工作才能檢閱,而且有一些限制:

  1. 除非您明確指示 GitHub Copilot 新增 CSS 樣式,否則通常不會包含 CSS 樣式。
  2. 如果您要求 Copilot 將 Bing 地圖 Web SDK 程式代碼轉譯成 Azure 地圖服務 Web SDK 程式代碼,通常會產生不佳的結果,因為兩者之間並不總是一對一對應。
  3. 您可能會偶爾遇到不完全錯誤,而且需要偵錯技巧和一些試用和錯誤。

結論

本操作說明指南示範如何使用 GitHub Copilot 為您的應用程式產生代碼段。 將應用程式從 Bing 地圖 for Enterprise 移轉至 Azure 地圖服務 時,這項功能很有説明。

我們已涵蓋下列各項:

  • 以清楚的句子撰寫提示。
  • 提供詳細的逐步指示。
  • 包含 Azure 地圖服務 API 要求輸入和回應輸出的範例。

下一步

探索其他進階提示工程技術,以協助您精簡提示。