缩放至地图上下拉框中的选定要素



我已经发布了 wfs 图层,然后按 wfs 图层属性填充下拉框,现在我希望当用户单击下拉框的值时,它将缩放到地图上 wfs 图层的要素

到目前为止,我已经做到了,

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());
});

但是当我从下拉列表中选择时,它不会缩放到该功能也给出了错误,

Cannot read property 'getGeometry' of undefined

问题是您使用的是选项的text而不是value。换句话说,您使用了错误的索引,state功能的属性。

一个简单的更改应该可以解决它,

var b = $('#sel1').val();

这里有一个完整的例子,

<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.3.1/css/ol.css" type="text/css">
<style>
.map {
height: 400px;
width: 100%;
}
#countries {
margin-top: .5rem;
margin-bottom: .5rem;
height: 2rem;
}
</style>
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.3.1/build/ol.js"></script>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<title>Select & Zoom to Country</title>
</head>
<body>
<select id="countries"></select>
<div id="map" class="map"></div>
<script type="text/javascript">
$(function () {

const vector = new ol.layer.Vector({
source: new ol.source.Vector()
});
const map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
vector
],
view: new ol.View({
center: ol.proj.fromLonLat([37.41, 8.82]),
zoom: 4
})
});
$.getJSON(
'https://openlayers.org/en/latest/examples/data/geojson/countries.geojson',
function (data) {
loadFeatures(data);
}
);
function loadFeatures(data) {
// load vector source
vector.getSource().addFeatures(new ol.format.GeoJSON().readFeatures(data));

const features = vector.getSource().getFeatures();
// add select options
$.each(features, function(i, v) {
$('#countries').append($('<option></option>').val(i).html(v.get('name')));
});
$('#countries').on('change', function() {
const selected = $('#countries').val();
const extent = vector.getSource().getFeatures()[selected]
.getGeometry().getExtent();
map.getView().fit(extent,map.getSize());
});
}
});
</script>
</body>
</html>

创建示例时,我意识到您在尝试缩放到该功能时出错,视图的功能fit

相关内容

  • 没有找到相关文章

最新更新