首页 > 解决方案 > 如何在 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);

标签: javascripthtmliframeleafletgeolocation

解决方案


使用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 的完整示例


推荐阅读