Reputation: 183
I have published wfs layer then populate the dropdown box by wfs layer attribute now I want when user click on the value of dropdown box it will zoom to the feature of wfs layer on the map
so far i have done this,
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());
});
but when I select from dropdown it does not zoom to the feature also gives the error,
Cannot read property 'getGeometry' of undefined
Upvotes: 0
Views: 717
Reputation: 5270
The problem is that you are using the text
of the option instead of the value
. In other words you are using a wrong index, state
property of the feature.
One simple change should fix it,
var b = $('#sel1').val();
Here you have a full example,
<!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>
When creating the example I realize you have an error when trying to zoom to the feature, the function of the view is fit
.
Upvotes: 1