javascript - 如何在 iframe 中使用 Leaflet.js 中的地图
问题描述
我正在尝试使用 iframe 将我的Leaflet地图标记定位在用户设备所在的位置,并使用地理定位 API。这是因为此错误消息ERROR(1): Geolocation has been disabled in this document by permissions policy.
。我试图在入门页面上包含来自 Leaflet.js 文档的地图的 div;包含在我的 iframe 元素中,属性为allow="geolocation"
,但这似乎不起作用,有人可以帮忙吗?
这是假设获取用户位置的代码
function success(position) {
var crd = position.coords;
console.log('Your current position is:');
console.log(`Latitude : ${crd.latitude}`);
console.log(`Longitude: ${crd.longitude}`);
console.log(`More or less ${crd.accuracy} meters.`);
}
function error(err) {
console.warn(`ERROR(${err.code}): ${err.message}`);
}
navigator.geolocation.getCurrentPosition(success, error, options);
解决方案
使用leaflejs中内置的定位功能不是更好吗?您遇到的错误也可能是因为CORS有问题
map
.locate({
// https://leafletjs.com/reference-1.7.1.html#locate-options-option
setView: true,
enableHighAccuracy: true,
})
// if location found show marker and circle
.on('locationfound', (e) => {
console.log(e);
// marker
const marker = L.marker([e.latitude, e.longitude]).bindPopup(
'Your are here :)'
);
// circle
const circle = L.circle([e.latitude, e.longitude], e.accuracy / 2, {
weight: 2,
color: 'red',
fillColor: 'red',
fillOpacity: 0.1,
});
// add marker
map.addLayer(marker);
// add circle
map.addLayer(circle);
})
// if error show alert
.on('locationerror', (e) => {
console.log(e);
alert('Location access denied.');
});
这是使用 iframe 的完整示例。
推荐阅读
- modeling - 在 GAMS 中创建具有移动索引间隙的变量的方程求和
- ios - 向可滑动行 iOS 15 添加警报
- reactjs - 我应该在我的反应项目中导入按钮之类的组件吗
- pdf - Ghostscript txt文件到pdf
- java - 创建没有子子项目“lib”或“app”的gradle子项目
- java - 您指定的目标需要执行项目,但此目录中没有 POM
- linux - 如何打印文件慢?
- android - 如何正确共享文件 android 11
- c# - Add-Migration 自动设置 'onDelete: ReferentialAction.Restrict);'
- ios - 如何创建自定义段顶部选项卡视图控制器?(迅速)