如何在 iframe 中使用 Leaflet.js 中的地图

Posted

技术标签:

【中文标题】如何在 iframe 中使用 Leaflet.js 中的地图【英文标题】:How to use a map from Leaflet.js inside an iframe 【发布时间】:2021-04-23 15:45:04 【问题描述】:

我正在尝试使用 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);

【问题讨论】:

你找到解决方案了吗? 【参考方案1】:

使用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 的完整 example。

【讨论】:

以上是关于如何在 iframe 中使用 Leaflet.js 中的地图的主要内容,如果未能解决你的问题,请参考以下文章