Javascript 缩放到地图上下拉框中选定的要素
我已经发布了wfs图层,然后通过wfs图层属性填充下拉框。现在我想当用户单击下拉框的值时,它将缩放到地图上wfs图层的特征 到目前为止,我已经做到了Javascript 缩放到地图上下拉框中选定的要素,javascript,openlayers,Javascript,Openlayers,我已经发布了wfs图层,然后通过wfs图层属性填充下拉框。现在我想当用户单击下拉框的值时,它将缩放到地图上wfs图层的特征 到目前为止,我已经做到了 function loadFeatures(json) { features = new ol.format.GeoJSON().readFeatures(json, { dataProjection: 'EPSG:4326', featureProjection: projection });
function loadFeatures(json) {
features = new ol.format.GeoJSON().readFeatures(json, {
dataProjection: 'EPSG:4326',
featureProjection: projection
});
sourceWFS.addFeatures(features);
var i;
var a;
att = sourceWFS.getFeatures();
for (i = 0; i < att.length;i++) {
str[i] = att[i].get("State");
}
$.each(str, function(val, text) {
$('#sel1').append( $('<option></option>').val(val).html(text) )
});
}
$('#sel1').on('change', function() {
var b = $('#sel1 :selected').text();
var extent = att[b].getGeometry().getExtent();
map.getView().fitExtent(extent,map.getSize());
});
但当我从下拉列表中选择时,它不会缩放到该功能,也会出现错误
无法读取未定义的属性“getGeometry”问题在于您使用的是选项的文本而不是值。换句话说,您使用了错误的索引、特性的状态属性 一个简单的改变就能解决这个问题
var b = $('#sel1').val();
这里有一个完整的例子
.地图{
高度:400px;
宽度:100%;
}
国家{
边缘顶部:.5rem;
边缘底部:.5rem;
高度:2em;
}
选择并缩放到国家/地区
$function{
常量向量=新的ol.layer.vector{
来源:新ol.source.Vector
};
常量映射=新ol.map{
目标:“地图”,
图层:[
新ol.layer.Tile{
来源:new ol.source.OSM
},
矢量
],
视图:新ol.view{
中心:Lonlat的其他项目[37.41,8.82],
缩放:4
}
};
$.getJSON
'https://openlayers.org/en/latest/examples/data/geojson/countries.geojson',
函数数据{
载荷特性数据;
}
;
函数加载特性数据{
//负载矢量源
vector.getSource.addFeaturesnew ol.format.GeoJSON.readFeaturesdata;
const features=vector.getSource.getFeatures;
//添加选择选项
$.eachfeatures,functioni,v{
$'countries'。追加$.vali.htmlv.get'name';
};
$'countries'。关于'change',函数{
所选常量=$'countries'.val;
常量范围=vector.getSource.getFeatures[选定]
.getGeometry.getExtent;
map.getView.fitextent,map.getSize;
};
}
};
加载选项时是否可以添加零件?@cabesuon我已编辑代码否无效仍然出现错误[b]。getGeometry不是函数请显示b的值。。只是一个简单的控制台。。但是我刚刚意识到没有必要:selected,check edit获取dropdownvar b的第一个值的索引应该获取selected值的索引您是否使用了我所做的编辑,$myselect.val;应返回所选的值