I have a vector layer which i statically load all the features from the JSON file. What I want to do is to create layers dynamically based on the user input.
The user will choose district code, for example, and when button is clicked it will create the layer and zoom to the specified extent (call the ZoomToParcel
function) . I haven't found any example in the docs.
var getDistrict, getTownVal, getQuarterVal; //this is user input (suppose they are dynamic)
var vector = new ol.layer.Vector({
source: new ol.source.Vector({
url: 'getjson.json', //loaded on client
format: new ol.format.GeoJSON()
}),style:style_simple
//,extent:ol.proj.transformExtent([...], 'EPSG:4326', 'EPSG:3857') //This should be dynamic
});
var map = new ol.Map({
target: 'map',
layers: [roadlayer,vector],
controls: ol.control.defaults().extend([new ol.control.ScaleLine()]),
view: new ol.View({
center: ol.proj.fromLonLat([33.33386, 35.14710]),
zoom: 14,
maxZoom: 19
})
});
function ZoomToParcel(){ //the extent here should be dynamic
let extent = vector.getExtent() || vector.getSource().getTileGrid().getExtent();
map.getView().fit(extent,{duration: 1590},map.getSize());
}
HTML:
<p><input type="text"> District</p>
<p><input type="text"> Town</p>
<p><input type="text"> Quarter</p>
<!-- etc... -->
<button onclick="ZoomToParcel()" class="btn btn-primary">SEARCH</button>
I log the (e) inside the select event, see the dist_code inside the values_ array:
UPDATE: Mike's answer helped with a bit modification, i make the if statement directly in the style. The filtering works fine, but by default the map should not show any layer (only baselayer).
var style_simple = function (feature, resolution) {
let featureParcel = feature.get("parcel_nbr")+"";
let featureDist = feature.get("dist_code")+"";
if(featureDist == 1) { //show districts with code 1
return new ol.style.Style({
fill: new ol.style.Fill({
color: 'khaki'
}),
stroke: new ol.style.Stroke({
color: 'blue',
width: 2
}),
text: new ol.style.Text({
text: featureParcel,
font: '13px Calibri,sans-serif',
fill: new ol.style.Fill({
color: 'blue'
})
})
});
}
}
As Mike suggested, Instead of re-loading the geojson for each change it is easier to filter the features on that property, in the style function so only the one we are interested in are displayed, and when setting the extent.
The user input is dynamic getDistrict
(think of it as a drop down with 5-6 districts)
The point is to be able to update the map when input changes. I am a little confused where i should put the change event and how i can update the style accordingly