我正在尝试在 OpenLayers 3
map 上添加标记。
我找到的唯一例子是 this OpenLayers
示例中的一个 list .
但是这个例子使用了ol.Style.Icon而不是像 OpenLayers.Marker 这样的东西在 OpenLayers 2
中。
第一个问题
唯一的区别是您必须设置图片 Url,但这是添加标记的唯一方法吗?
此外,OpenLayers 3
似乎没有标记图像,所以如果除了 ol.Style.Icon
第二个问题
如果有人能给我一个在加载 map 后添加标记或图标的函数示例,那就太好了。
根据我在示例中的理解,他们为图标创建了一个图层
var iconFeature = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.transform([-72.0704, 46.678], 'EPSG:4326', 'EPSG:3857')),
name: 'Null Island',
population: 4000,
rainfall: 500
});
var iconStyle = new ol.style.Style({
image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
anchor: [0.5, 46],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
opacity: 0.75,
src: 'data/icon.png'
}))
});
iconFeature.setStyle(iconStyle);
var vectorSource = new ol.source.Vector({
features: [iconFeature]
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource
});
然后他们在初始化 map 的时候设置了图标层
var map = new ol.Map({
layers: [new ol.layer.Tile({ source: new ol.source.OSM() }), vectorLayer],
target: document.getElementById('map'),
view: new ol.View2D({
center: [0, 0],
zoom: 3
})
});
如果我想添加很多标记,是否必须为每个标记创建 1 个图层?
如何向图层添加多个标记?我不知道这部分会是什么样子 喜欢
var vectorSource = new ol.source.Vector({
features: [iconFeature]
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource
});
谢谢
最佳答案
Q1。标记在 OpenLayers 2 中被认为已弃用,尽管这在文档中不是很明显。相反,您应该使用 OpenLayers.Feature.Vector 并将 externalGraphic 设置为其样式中的某个图像源。这个概念已转移到 OpenLayers 3,因此没有标记类,它是按照您引用的示例完成的。
Q2。 ol.source.Vector 采用一组特征,注意这一行,features: [iconFeature],因此您可以创建一组图标特征并向其添加特征,例如:
var iconFeatures=[];
var iconFeature = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.transform([-72.0704, 46.678], 'EPSG:4326',
'EPSG:3857')),
name: 'Null Island',
population: 4000,
rainfall: 500
});
var iconFeature1 = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.transform([-73.1234, 45.678], 'EPSG:4326',
'EPSG:3857')),
name: 'Null Island Two',
population: 4001,
rainfall: 501
});
iconFeatures.push(iconFeature);
iconFeatures.push(iconFeature1);
var vectorSource = new ol.source.Vector({
features: iconFeatures //add an array of features
});
var iconStyle = new ol.style.Style({
image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
anchor: [0.5, 46],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
opacity: 0.75,
src: 'data/icon.png'
}))
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource,
style: iconStyle
});
显然,通过将所有 ol.Feature 创建放在一个基于某些数据源的循环中,可以更优雅地处理这个问题,但我希望这展示了这种方法。另请注意,您可以将样式应用于 ol.layer.Vector,以便将其应用于添加到图层的所有要素,而不必在单个要素上设置样式,假设您希望它们是显然是一样的。
编辑:这个答案似乎不起作用。这是更新的 fiddle它通过使用 vectorSource.addFeature 将特征(图标)添加到循环中的空矢量源来工作,然后将全部添加到图层矢量。在更新我原来的答案之前,我会等着看这是否适合你。
关于javascript - 如何使用 OpenLayers 3 添加标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24315801/