【问题标题】:Add an icon on the map with OpenLayers 5使用 OpenLayers 5 在地图上添加图标
【发布时间】:2021-07-07 19:37:33
【问题描述】:

我正在尝试使用 OpenLayers 5 在地图上添加图标。

我尝试关注网站上的 Openlayers 示例,但没有成功 (https://openlayers.org/en/latest/examples/icon.html)

我认为问题可能出在样式上,因为当我从功能中删除它时,地图上会显示一个点,但是当我尝试向该点添加样式(它是图标)时,什么也没有显示在地图上。

我在下面发送我使用的代码:

import Point from 'ol/geom/Point'
import { Icon, Style } from 'ol/style.js'
// or
// import Icon from 'ol/style/Icon'
// import Style from 'ol/style/Style'

...

const vectorMarkerSource = new VectorSource()

const vectorMarkerGroup = new VectorLayer({
    source: vectorMarkerSource
})

...

this.olmap = new Map({
    target: 'map',
    layers: [
        baseLayerGroup, vectorMarkerGroup
    ],
    view: this.view
})

...

var iconFeature = new Feature({
    geometry: new Point([0, 0]),
    projection: 'EPSG:4326'
})

// I've already tried the two options of 'src'
var iconStyle = new Style({
    image: new Icon(/** @type {module:ol/style/Icon~Options} */ ({
        anchor: [0.5, 46],
        anchorXUnits: 'fraction',
        anchorYUnits: 'pixels',
        src: '@/assets/img/marker/marker-blue.png'
        // src: '../../assets/img/marker/marker-blue.png'
    }))
})

iconFeature.setStyle(iconStyle)

vectorMarkerSource.addFeature(iconFeature)

提前谢谢你。

【问题讨论】:

  • 控制台是否显示 marker-blue.png 的 404 错误?
  • 不,它没有。在控制台上什么也没有显示。幸运的是,我不小心找到了这个问题的解决方案,并在下面回答。非常感谢您的帮助。

标签: icons openlayers point openlayers-5


【解决方案1】:

我偶然发现了一个解决方案。我正在阅读另一个代码来解决另一个问题,在此代码上,创建者使用以下方法插入图标。

import markerIconBlue from '@/assets/img/marker/marker-icon-2x-blue.png'

var iconStyle = new Style({
    image: new Icon(/** @type {module:ol/style/Icon~Options} */ ({
        anchor: [0.5, 46],
        anchorXUnits: 'fraction',
        anchorYUnits: 'pixels',
        src: markerIconBlue
    }))
})

幸运的是,这种方法对我有用,我希望这对其他人有所帮助。

【讨论】:

  • 您能解释一下如何将 png 导入您的代码吗?您是否必须在 angular.json 文件或其他地方实现某些特定性?
  • 我已经使用上面的代码在我的代码中导入了 png。我在@/assets 文件夹中添加了我的png 文件,然后我使用import variable from <path> 将其导入,并在new Icon 中添加了variable
猜你喜欢
  • 1970-01-01
  • 2015-12-23
  • 2013-01-28
  • 1970-01-01
  • 2022-08-15
  • 1970-01-01
  • 2018-12-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多