使用 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 中所述。骨架包括一个模糊的小地图,以增加真实感,并且在 <amp-img>
加载实际图像时也使用该地图,以防止在删除占位符时出现闪烁。
您所在的地区是 {{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 编写