我有一个包含许多不同位置、名称和图片以及经纬度的数组。如果我直接把它们放到地图上,会变得混乱。因此,我尝试使用聚类。
首先创建要素:
我随后使用一些图标来为集群添加样式。
我后来有一个onclick方法,应该从Feature中获取“name”,但它只能打印出几何图形,就像对象上的名称从Clusters中消失了。例如,执行
addOverlay方法无法获取要素的名称,返回值为“undefined”,这非常奇怪。有帮助吗?请求帮助!就像将要素添加到聚类中后,它们似乎停止存在一样。
首先创建要素:
for(var i = 0; i < points.length; i++){
features[i] = new ol.Feature({
population: 4000,
name : points[i].name,
geometry: new ol.geom.Point(
ol.proj.transform([
points[i].long,
points[i].lat],
'EPSG:4326', oProjection))
});
}
我接着用带有特征的向量填充聚类:
var vSource = new ol.source.Vector({ features: features});
var vFeatures = vSource.getFeatures();
var clusterSource = new ol.source.Cluster({
distance: 20,
source: vSource});
我随后使用一些图标来为集群添加样式。
var clusters = new ol.layer.Vector({
source: clusterSource,
style : new ol.style.Style({
image: new ol.style.Icon(({
src: 'image/image.png'})),
text: new ol.style.Text({
font: '18px Helvetica, Arial Bold, sans-serif',
text: size.toString(),
fill: new ol.style.Fill({
color: '#fff'
})
})
map.add(clusters)
我后来有一个onclick方法,应该从Feature中获取“name”,但它只能打印出几何图形,就像对象上的名称从Clusters中消失了。例如,执行
clusterSource.getFeatures()
返回一个空向量[]
。function addOverlays(points){
for(var i = 0; i<points.length;i++){
var element = document.getElementById(points[i].id);
var popup = new ol.Overlay({
element: element,
positioning: 'bottom-center',
stopEvent: false
});
map.addOverlay(popup);
// display popup on click
}
// display popup on click
map.on('click', function(evt) {
var feature = map.forEachFeatureAtPixel(evt.pixel,
function(feature, layer) {
console.log("feature on click: ",feature);
return feature;
});
if (feature) {
var geometry = feature.getGeometry();
var coord = geometry.getCoordinates();
popup.setPosition(coord);
console.log(feature.get('name'));
$(element).popover({
'placement': 'bottom',
'html': true,
'content': feature.get('name') //THIS IS THE TROUBLE
});
$(element).popover('show');
} else {
$(element).popover('destroy');
}
});
}
addOverlay方法无法获取要素的名称,返回值为“undefined”,这非常奇怪。有帮助吗?请求帮助!就像将要素添加到聚类中后,它们似乎停止存在一样。
feature.get('name')
替换为feature.get('features').get('name')
来解决它。希望能有所帮助。 - Hicham Zouarhi