pet*_*tur 2 javascript openlayers-3
我有一个阵列,有很多不同的位置,有名字和图片,当然还有经度和纬度.如果我将它们直接放在地图上,就会变得杂乱无章.所以我尝试使用集群.
从创建功能开始:
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))
});
}
Run Code Online (Sandbox Code Playgroud)
然后,我使用具有以下功能的向量填充集群:
var vSource = new ol.source.Vector({ features: features});
var vFeatures = vSource.getFeatures();
var clusterSource = new ol.source.Cluster({
distance: 20,
source: vSource});
Run Code Online (Sandbox Code Playgroud)
然后我用一些图标设置簇的样式
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)
Run Code Online (Sandbox Code Playgroud)
我后来有一个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');
}
});
}
Run Code Online (Sandbox Code Playgroud)
addOverlay方法无法获取该功能的名称,它返回"undefined",这很奇怪.救命?有什么帮助吗?就像功能在群集中添加时停止存在一样.
小智 9
因此,通过群集,OL3会创建一个新功能,用于包装其下的所有群集功能.如果查看聚类功能,可以在values属性下看到:
values_: Object
features: Array[19]
geometry: ol.geom.Point
Run Code Online (Sandbox Code Playgroud)
这就是为什么getFeatures()
不起作用的原因,在使用群集功能时,它们在创建时只有这两个值.
function isCluster(feature) {
if (!feature || !feature.get('features')) {
return false;
}
return feature.get('features').length > 1;
}
map.on('click', function(evt) {
var feature = map.forEachFeatureAtPixel(evt.pixel,
function(feature) { return feature; });
if (isCluster(feature)) {
// is a cluster, so loop through all the underlying features
var features = feature.get('features');
for(var i = 0; i < features.length; i++) {
// here you'll have access to your normal attributes:
console.log(features[i].get('name'));
}
} else {
// not a cluster
console.log(feature.get('name'));
}
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6947 次 |
最近记录: |