搭配 amp-list 的地理位置定位
簡介
如果您需要的地理位置定位支援比 amp-geo 擴充功能提供的更精細,您可以透過後端的地理位置定位邏輯和 amp-list 實作以地理位置為基礎的功能。這會增加額外的 XHR 要求,但您可以使用預留位置屬性中的骨架版面配置,來減輕負面的使用者體驗影響。
設定
匯入 amp-list
元件...
<script async custom-element="amp-list" src="https://cdn.ampproject.org/v0/amp-list-0.1.js"></script>
... 以及 amp-mustache
元件
<script async custom-template="amp-mustache" src="https://cdn.ampproject.org/v0/amp-mustache-0.2.js"></script>
地理位置搜尋結果
amp-list
向伺服器後端發出要求,後端會執行以 IP 為基礎的地理位置定位,並傳回相關的搜尋結果。在此示範中,它會呼叫 API 以取得附近的城市。後端會傳回 JSON 結果,而 amp-list
會使用 amp-mustache
轉譯這些結果。後端會發出兩個遠端 API 呼叫 (並新增 500 毫秒的模擬延遲);為了減輕此延遲對使用者體驗的影響,我們使用 amp-list
的 placeholder
來配置骨架。
由於我們需要為 amp-list 建立初始的固定大小,因此我們手動計算出每張卡片為 100 像素 + 15 像素邊界,而標題為 16 像素 + 20 像素邊界
16px + 20px + (5 * (100 + 15px)) = 611px
預留位置清單項目主要使用 CSS 來繪製骨架元素,如 CSS-Tricks 中所述。骨架包含一個微小的模糊地圖,以增加真實感,並且在地圖載入實際圖片時也會使用該地圖,以防止在移除預留位置時出現閃爍。
您位於 {{location}}
- {{#results}}
-
{{placeName}}
{{adminName1}}
{{countryCode}} {{/results}}
您位於
<amp-list class="geolist-preview" width="auto" height="640" layout="fixed-height" noloading src="https://caramel-wolf.glitch.me//location-specific-results.json" binding="no" single-item items=".">
<template type="amp-mustache" id="amp-template-id">
<h3>You are in {{location}}</h3>
<ul class="results">
{{#results}}
<li>
<amp-img alt="{{placeName}} Map" noloading layout="fixed" width="150" height="100" src="https://maps.googleapis.com/maps/api/staticmap?markers={{lat}},{{lng}}&zoom=9&size=150x100&maptype=roadmap&key=AIzaSyByT-0aYa-nEF0gGqJHNpEEK1bus00losI">
</amp-img>
<p>
<strong>{{placeName}}</strong><br>
{{adminName1}}<br>
{{countryCode}}
</p>
</li>
{{/results}}
</ul>
</template>
<div placeholder>
<h3>You are in <span class="placeholder"></span></h3>
<ul class="results">
<li></li><li></li><li></li><li></li><li></li>
</ul>
</div>
</amp-list>
如果本頁面的說明沒有涵蓋您的所有問題,請隨時與其他 AMP 使用者聯絡,討論您的確切使用案例。
前往 Stack Overflow 有未說明的特色功能嗎?AMP 專案大力鼓勵您的參與和貢獻!我們希望您能成為我們開放原始碼社群的長期參與者,但我們也歡迎您針對您特別關注的問題提供一次性的貢獻。
在 GitHub 上編輯範例-
作者: @jamesshannon