如何在 openLayer 地图中加载本地 gpx 文件?

How load local gpx file in a openLayer map?

我觉得标题很清楚,我正在使用 openLayer 库 (v4.6.5) 并且我正在尝试在加载页面时在我的地图中加载本地 GPX 文件。在官方文档中,在 GPX 数据示例 (https://openlayers.org/en/latest/examples/gpx.html?q=data) 中,使用 url.

似乎非常简单
var vector = new ol.layer.Vector({
    source: new ol.source.Vector({
      url: 'https://openlayers.org/en/v4.6.5/examples/data/gpx/fells_loop.gpx',
      format: new ol.format.GPX()
    }),
    style: function(feature) {
      return style[feature.getGeometry().getType()];
    }
  });

我的问题是,我需要在 ol.source.Vector object 中设置什么选项来加载本地 GPX 文件,而不是设置 url 选项?提前致谢。

解决方案 1

只需使用 OpenLayers 库中提供的拖放组件即可。演示于 https://openlayers.org/en/latest/examples/drag-and-drop.html(拖放 GPX 进行测试)

解决方案 2

如果您 want/need 手动执行操作,则需要删除 URL 引用和格式。

然后,当您执行拖放(或其他操作)然后使用

解析它时,您将获得 GPS 文件内容
var GPXfeatures = (new ol.format.GPX()).readFeatures('yourGPXstring', {featureProjection: 'EPSG:3857'})

然后使用

将特征添加到源中
vector.getSource().addFeatures(GPXfeatures)