共用方式為


在地圖上新增快顯

本文說明如何在地圖上的某個點新增快顯。

了解程式碼

下列程式碼會使用符號圖層,將具有 namedescription 屬性的點特徵新增至地圖。 系統會建立快顯類別的執行個體,但是不會顯示。 滑鼠事件會新增至符號圖層,以觸發開啟和關閉快顯。 當標記符號動態顯示時,快顯的 position 屬性會以標記的位置更新,而 content 選項會以一些 HTML 來更新,會包裝動態顯示點特徵的 namedescription 屬性。 然後,快顯會使用其 open 函式在地圖上顯示。

//Define an HTML template for a custom popup content laypout.
var popupTemplate = '<div class="customInfobox"><div class="name">{name}</div>{description}</div>';

//Create a data source and add it to the map.
var dataSource = new atlas.source.DataSource();
map.sources.add(dataSource);

dataSource.add(new atlas.data.Feature(new atlas.data.Point([-122.1333, 47.63]), {
  name: 'Microsoft Building 41', 
  description: '15571 NE 31st St, Redmond, WA 98052'
}));

//Create a layer to render point data.
var symbolLayer = new atlas.layer.SymbolLayer(dataSource);

//Add the polygon and line the symbol layer to the map.
map.layers.add(symbolLayer);

//Create a popup but leave it closed so we can update it and display it later.
popup = new atlas.Popup({
  pixelOffset: [0, -18],
  closeButton: false
});

//Add a hover event to the symbol layer.
map.events.add('mouseover', symbolLayer, function (e) {
  //Make sure that the point exists.
  if (e.shapes && e.shapes.length > 0) {
    var content, coordinate;
    var properties = e.shapes[0].getProperties();
    content = popupTemplate.replace(/{name}/g, properties.name).replace(/{description}/g, properties.description);
    coordinate = e.shapes[0].getCoordinates();

    popup.setOptions({
      //Update the content of the popup.
      content: content,

      //Update the popup's position with the symbol's coordinate.
      position: coordinate

    });
    //Open the popup.
    popup.open(map);
  }
});

map.events.add('mouseleave', symbolLayer, function (){
  popup.close();
});

重複使用具有多個點的快顯

在某些情況下,最佳方法是建立一個快顯並重複使用。 例如,您可能有大量的點,而且想要一次只顯示一個快顯。 藉由重複使用快顯,應用程式所建立的 DOM 元素數目就會大幅減少從而提升效能。 下列範例會建立 3 點特徵。 如果選取其中任一個,則會顯示一個快顯,其中具有該點特徵的內容。

如需一個完整功能範例,示範如何建立一個快顯並重複使用,而不是為每個點特徵建立快顯,請參閱 Azure 地圖服務範例中的重複使用具有多個釘選的快顯。 如需此範例的原始程式碼,請參閱重複使用具有多個釘選的快顯原始程式碼

A screenshot of map with three blue pins.

自訂快顯

根據預設,快顯具有白色背景、底部有指標箭號,以及右上角有關閉按鈕。 下列範例會使用快顯的 fillColor 選項,將背景色彩變更為黑色。 關閉按鈕可藉由將 CloseButton 選項設定為 false 來移除。 快顯的 HTML 內容從快顯邊緣使用填補的 10 像素。 文字會變成白色,因此可顯示在黑色背景上。

如需示範如何自訂快顯外觀的完整功能範例,請參閱 Azure 地圖服務範例中的自訂快顯。 如需此範例的原始程式碼,請參閱自訂快顯原始程式碼

A screenshot of map with a custom popup in the center of the map with the caption 'hello world'.

將快顯範本新增至地圖

快顯範本可讓您輕鬆地建立快顯的資料驅動版面配置。 下列各節示範如何使用各種快顯範本,使用特徵的屬性來產生格式化的內容。

注意

根據預設,使用快顯範本轉譯的所有內容都會在 iframe 內沙箱化為安全性功能。 不過,有一些限制:

  • 所有指令碼、表單、指標鎖定和頂端導覽功能都會停用。 按一下時,允許在新的索引標籤中開啟連結。
  • 不支援 iframe 上 srcdoc 參數的舊版瀏覽器,將僅限於轉譯少量的內容。

如果您信任載入快顯的資料,並且可能想要將這些指令碼載入快顯中,就可以存取您的應用程式,可以藉由將快顯範本 sandboxContent 選項設定為 false 來停用此功能。

String 範本

String 範本會將預留位置取代為特徵屬性的值。 特徵的屬性不需要指派 String 類型的值。 例如,value1 會保留整數。 這些值接著會傳遞至 popupTemplate 的內容屬性。

numberFormat 選項會指定要顯示的數字格式。 如果未指定 numberFormat,則程式碼會使用快顯範本日期格式。 numberFormat 選項會使用 Number.toLocaleString 函式來格式化數字。 若要格式化大量數字,請考慮使用 numberFormat 選項搭配 NumberFormat.format 中的函式。 例如,下列程式碼片段會使用 maximumFractionDigits 將小數位數限制為兩個。

注意

String 範本只能透過一種方式來轉譯影像。 首先,String 範本必須有影像標記。 傳遞至影像標記的值應該是影像的 URL。 然後,String 範本必須在 HyperLinkFormatOptions 中將 isImage 設定為 true。 isImage 選項會指定超連結適用於影像,而超連結將會載入影像標記中。 按一下超連結時,影像就會開啟。

var templateOptions = {
  content: 'This template uses a string template with placeholders.<br/><br/> - Value 1 = {value1}<br/> - Value 2 = {value2/subValue}<br/> - Array value [2] = {arrayValue/2}',
  numberFormat: {
    maximumFractionDigits: 2
  }
};

var feature = new atlas.data.Feature(new atlas.data.Point([0, 0]), {
    title: 'Template 1 - String template',
    value1: 1.2345678,
    value2: {
        subValue: 'Pizza'
    },
    arrayValue: [3, 4, 5, 6]
});

var popup = new atlas.Popup({
  content: atlas.PopupTemplate.applyTemplate(feature.properties, templateOptions),
  position: feature.geometry.coordinates
});

PropertyInfo 範本

PropertyInfo 範本會顯示特徵的可用屬性。 label 選項會指定要向使用者顯示的文字。 如果未指定 label,則會顯示超連結。 但是,如果超連結是影像,則會顯示指派給 "alt" 標籤的值。 dateFormat 會指定日期的格式,如果未指定日期格式,則日期會轉譯為字串。 hyperlinkFormat 選項會轉譯可點選的連結,同樣地,email 選項可用來轉譯可點選的電子郵件地址。

在 PropertyInfo 範本向使用者顯示內容之前,會以遞迴方式檢查是否確實為該特徵定義屬性。 也會忽略顯示樣式和標題屬性。 例如,不會顯示 colorsizeanchorstrokeOpacityvisibility。 因此,一旦屬性路徑檢查在後端完成,PropertyInfo 範本就會以資料表格式顯示內容。

var templateOptions = {
  content: [
    {
        propertyPath: 'createDate',
        label: 'Created Date'
    },
    {
        propertyPath: 'dateNumber',
        label: 'Formatted date from number',
        dateFormat: {
          weekday: 'long',
          year: 'numeric',
          month: 'long',
          day: 'numeric',
          timeZone: 'UTC',
          timeZoneName: 'short'
        }
    },
    {
        propertyPath: 'url',
        label: 'Code samples',
        hideLabel: true,
        hyperlinkFormat: {
          lable: 'Go to code samples!',
          target: '_blank'
        }
    },
    {
        propertyPath: 'email',
        label: 'Email us',
        hideLabel: true,
        hyperlinkFormat: {
          target: '_blank',
          scheme: 'mailto:'
        }
    }
  ]
};

var feature = new atlas.data.Feature(new atlas.data.Point([0, 0]), {
    title: 'Template 2 - PropertyInfo',
    createDate: new Date(),
    dateNumber: 1569880860542,
    url: 'https://samples.azuremaps.com/',
    email: 'info@microsoft.com'
}),

var popup = new atlas.Popup({
  content: atlas.PopupTemplate.applyTemplate(feature.properties, templateOptions),
  position: feature.geometry.coordinates
});

多個內容範本

特徵也可能使用 String 範本和 PropertyInfo 範本的組合來顯示內容。 在此情況下,String 範本會在白色背景轉譯預留位置值。 而 PropertyInfo 範本會在資料表內轉譯全形影像。 此範例中的屬性類似於我們在先前範例中說明的屬性。

var templateOptions = {
  content: [
    'This template has two pieces of content; a string template with placeholders and a array of property info which renders a full width image.<br/><br/> - Value 1 = {value1}<br/> - Value 2 = {value2/subValue}<br/> - Array value [2] = {arrayValue/2}',
    [{
      propertyPath: 'imageLink',
      label: 'Image',
      hideImageLabel: true,
      hyperlinkFormat: {
        isImage: true
      }
    }]
  ],
  numberFormat: {
    maximumFractionDigits: 2
  }
};

var feature = new atlas.data.Feature(new atlas.data.Point([0, 0]), {
    title: 'Template 3 - Multiple content template',
    value1: 1.2345678,
    value2: {
    subValue: 'Pizza'
    },
    arrayValue: [3, 4, 5, 6],
    imageLink: 'https://samples.azuremaps.com/images/Pike_Market.jpg'
});

var popup = new atlas.Popup({
  content: atlas.PopupTemplate.applyTemplate(feature.properties, templateOptions),
  position: feature.geometry.coordinates
});

沒有已定義範本的點

當 Popup 範本未定義為 String 範本、PropertyInfo 範本或兩者的組合時,會使用預設設定。 當 titledescription 是唯一指派的屬性時,快顯範本會顯示白色背景、右上角有關閉按鈕。 而且,在小型和中型螢幕上,會在底部顯示箭號。 預設設定會在資料表中顯示除了 titledescription 以外的所有屬性。 即使回復到預設設定,快顯範本仍然可以以程式設計方式操作。 例如,使用者可以關閉超連結偵測,而預設設定仍會套用至其他屬性。

一旦執行,您就可以選取地圖上的點以查看快顯。 下列每個快顯範本的地圖上都有一個點:String 範本、PropertyInfo 範本和多個內容範本。 另外還有三點可示範範本如何使用預設設定來轉譯。

function InitMap()
{
  var map = new atlas.Map('myMap', {
      zoom: 2,
      view: "Auto",

    //Add authentication details for connecting to Azure Maps.
      authOptions: {
          authType: 'subscriptionKey',
          subscriptionKey: '{Your-Azure-Maps-Subscription-key}'
      }
  });

  //Wait until the map resources are ready.
  map.events.add('ready', function() {
    //Create a data source and add it to the map.
    var datasource = new atlas.source.DataSource();
    map.sources.add(datasource);

    //Add sample data.
    datasource.add([
      new atlas.data.Feature(new atlas.data.Point([-20, 20]), {
        title: 'No template - title/description',
        description: 'This point doesn\'t have a template defined, fallback to title and description properties.'
      }),

      new atlas.data.Feature(new atlas.data.Point([20, 20]), {
        title: 'No template - property table',
        message: 'This point doesn\'t have a template defined, fallback to title and table of properties.',
        randomValue: 10,
        url: 'https://samples.azuremaps.com/',
        imageLink: 'https://samples.azuremaps.com/images/Pike_Market.jpg',
        email: 'info@microsoft.com'
      }),

      new atlas.data.Feature(new atlas.data.Point([40, 0]), {
        title: 'No template - hyperlink detection disabled',
        message: 'This point doesn\'t have a template defined, fallback to title and table of properties.',
        randomValue: 10,
        url: 'https://samples.azuremaps.com/',
        email: 'info@microsoft.com',
        popupTemplate: {
          detectHyperlinks: false
        }
      }),

      new atlas.data.Feature(new atlas.data.Point([-20, -20]), {
        title: 'Template 1 - String template',
        value1: 1.2345678,
        value2: {
          subValue: 'Pizza'
        },
        arrayValue: [3, 4, 5, 6],
        popupTemplate: {
          content: 'This template uses a string template with placeholders.<br/><br/> - Value 1 = {value1}<br/> - Value 2 = {value2/subValue}<br/> - Array value [2] = {arrayValue/2}',
          numberFormat: {
            maximumFractionDigits: 2
          }
        }
      }),

      new atlas.data.Feature(new atlas.data.Point([20, -20]), {
        title: 'Template 2 - PropertyInfo',
        createDate: new Date(),
        dateNumber: 1569880860542,
        url: 'https://samples.azuremaps.com/',
        email: 'info@microsoft.com',
        popupTemplate: {
          content: [{
            propertyPath: 'createDate',
            label: 'Created Date'
          },
                    {
                      propertyPath: 'dateNumber',
                      label: 'Formatted date from number',
                      dateFormat: {
                        weekday: 'long',
                        year: 'numeric',
                        month: 'long',
                        day: 'numeric',
                        timeZone: 'UTC',
                        timeZoneName: 'short'
                      }
                    },
                    {
                      propertyPath: 'url',
                      label: 'Code samples',
                      hideLabel: true,
                      hyperlinkFormat: {
                        lable: 'Go to code samples!',
                        target: '_blank'
                      }
                    },
                    {
                      propertyPath: 'email',
                      label: 'Email us',
                      hideLabel: true,
                      hyperlinkFormat: {
                        target: '_blank',
                        scheme: 'mailto:'
                      }
                    }
                    ]
        }
      }),

      new atlas.data.Feature(new atlas.data.Point([0, 0]), {
        title: 'Template 3 - Multiple content template',
        value1: 1.2345678,
        value2: {
          subValue: 'Pizza'
        },
        arrayValue: [3, 4, 5, 6],
        imageLink: 'https://samples.azuremaps.com/images/Pike_Market.jpg',
        popupTemplate: {
          content: [
            'This template has two pieces of content; a string template with placeholders and a array of property info which renders a full width image.<br/><br/> - Value 1 = {value1}<br/> - Value 2 = {value2/subValue}<br/> - Array value [2] = {arrayValue/2}',
            [{
              propertyPath: 'imageLink',
              label: 'Image',
              hideImageLabel: true,
              hyperlinkFormat: {
                isImage: true
              }
            }]
          ],
          numberFormat: {
            maximumFractionDigits: 2
          }
        }
      }),
    ]);

    //Create a layer that defines how to render the points on the map.
    var layer = new atlas.layer.BubbleLayer(datasource);
    map.layers.add(layer);

    //Create a popup but leave it closed so we can update it and display it later.
    popup = new atlas.Popup();

    //Add a click event to the layer.
    map.events.add('click', layer, showPopup);
  });

  function showPopup(e) {
    if (e.shapes && e.shapes.length > 0) {
      var properties = e.shapes[0].getProperties();

      popup.setOptions({
        //Update the content of the popup.
        content: atlas.PopupTemplate.applyTemplate(properties, properties.popupTemplate),

        //Update the position of the popup with the pins coordinate.
        position: e.shapes[0].getCoordinates()
      });

      //Open the popup.
      popup.open(map);
    }
  }
}

A screenshot of map with six blue dots.

重複使用快顯範本

類似於重複使用快顯,您可以重複使用快顯範本。 當您只想要一次針對多個點顯示一個快顯範本時,此方法很有用。 重複使用快顯範本,可減少應用程式所建立的 DOM 元素數目,進而改善您的應用程式效能。 下列範例會針對三點使用相同的快顯範本。 如果選取其中任一個,則會顯示一個快顯,其中具有該點特徵的內容。

如需一個完整功能範例,示範如何重複使用單一快顯範本,搭配多個共用一組通用屬性欄位的特徵,請參閱 Azure 地圖服務範例中的重複使用快顯範本。 如需此範例的原始程式碼,請參閱重複使用快顯範本原始程式碼

A screenshot of a map showing Seattle with three blue pins to demonstrating how to reuse popup templates.

快顯可以開啟、關閉和拖曳。 快顯類別提供事件,以協助開發人員回應這些事件。 下列範例會醒目提示當使用者開啟、關閉或拖曳快顯時引發的事件。

如需示範如何將事件新增至快顯的完整功能範例,請參閱 Azure 地圖服務範例中的快顯事件。 如需此範例的原始程式碼,請參閱快顯事件原始程式碼

A screenshot of a map of the world with a popup in the center and a list of events in the upper left that are highlighted when the user opens, closes, or drags the popup.

下一步

深入了解本文使用的類別和方法:

請參閱下列推薦文章,了解完整程式碼範例: