Popup in WFS layer Openlayers - popup

Good Morning.
To work with wfs layer is it better to use leaflet or openlayers?
I have a code with openlayers that returns WFS from the geoserver. But I'm not able to show the attributes in popup. can anybody help me?
Thanks

You can try ol-ext ol/Overlay/PopupFeature to display feature attributes in a popup.
See example: https://viglino.github.io/ol-ext/examples/popup/map.popup.feature.html

Following the example of https://viglino.github.io/ol-ext/examples/popup/map.popup.feature.html, I have this code where my WFS layer contains the id and name attributes, however, it doesn't show anything in the popup
var vectorSource = new ol.source.Vector({
format: new ol.format.GeoJSON(),
url: function(extent) {
return 'http://localhost:8080/geoserver/teste/wfs?service=WFS&' +
version=1.1.0&request=GetFeature&typename=teste:MYLAYER&' +
'outputFormat=application/json&srsname=EPSG:4326&' +
'bbox=' + extent.join(',') + ',EPSG:4326';
},
strategy: ol.loadingstrategy.bbox
});
var vector = new ol.layer.Vector({
source: vectorSource,
style: new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'rgba(0, 0, 255, 1.0)',
width: 2
})
})
});
var layers = [
new ol.layer.Tile({source: new ol.source.OSM()}),
vector,
];
var map = new ol.Map({
layers: layers,
interactions: ol.interaction.defaults({ altShiftDragRotate:false, pinchRotate:false }),
target: 'map',
view: new ol.View({
center: ol.proj.fromLonLat([-46.444137, -23.713596]),
zoom: 12
})
});
var select = new ol.interaction.Select({
hitTolerance: 5,
multi: true,
condition: ol.events.condition.singleClick
});
map.addInteraction(select);
var popup = new ol.Overlay.PopupFeature({
popupClass: 'default anim',
select: select,
canFix: true,
template: {
title:
function(f) {
return f.get('nome')+' ('+f.get('id')+')';
},
attributes: // [ 'id', 'nome' ]
{
'nome': { title: 'Nome' },
'id': { title: 'Id' },
}
}
});
map.addOverlay (popup);

This is the popup code. I have 3 layers: layer1, layer2 and layer3.
For layer1, ID I want to show as ID. For layer2, I want to show ID as CODE and for other layers I don't want to show ID attribute.
How should I change the template? Thanks
var popup = new ol.Overlay.PopupFeature({
popupClass: 'default anim',
select: select_interaction,
canFix: true,
template: {
title:
function(f) {
return f.get('NAME')+' ('+f.get('ID')+')';
},
attributes:
{
'ID': { title: 'ID' },
// with prefix and suffix
'POP': {
title: 'População', // attribute's title
before: '', // something to add before
format: ol.Overlay.PopupFeature.localString(), // format as local string
after: ' hab.' // something to add after
},
}
}
});

#user12538529
You have to create a function and return the template for each case:
// Create templates
var templateID = { ... };
var templateCODE = { ... };
// Popup with a template function
var popup = new ol.Overlay.PopupFeature({
popupClass: 'default anim',
select: select_interaction,
canFix: true,
template: function(feature) {
var prop = feature.getProperties();
// Test if has property ID
if (prop.hasOwnProperty('ID')) return templateID;
// or property CODE
else if (prop.hasOwnProperty('CODE')) return templateCODE;
}
});

Related

infobox to pushpin via geocode, close all open infoboxs before opening new infobox

ok, here is my code
const members = [
{name: 'Abc Ijk', order: '646545', duration: '1.20h', createdOn: '02/03/2021 09:00 - 10:00', address: '1221 test Avenue Room 112 Portland OR 97204' },
{name: 'Xyz Opq', order: '646546', duration: '3.00h', createdOn: '02/03/2021 08:00 - 11:00', address: '945 nw street 852 Portland OR 97209' }
];
function loadEmpStatus() {
// var navigationBarMode = Microsoft.Maps.NavigationBarMode;
var map = new Microsoft.Maps.Map(document.getElementById('sdy-fserv-map'), {
/* No need to set credentials if already passed in URL */
// navigationBarMode: navigationBarMode.compact,
// supportedMapTypes: [Microsoft.Maps.MapTypeId.road, Microsoft.Maps.MapTypeId.aerial, Microsoft.Maps.MapTypeId.grayscale, Microsoft.Maps.MapTypeId.canvasLight],
supportedMapTypes: [Microsoft.Maps.MapTypeId.road, Microsoft.Maps.MapTypeId.aerial],
center: new Microsoft.Maps.Location(47.624527, -122.355255),
maxZoom: 11,
minZoom: 5
});
for( let row of members ) {
console.log(row);
doGeocode( map, row );
}
}
function doGeocode( map, data ) {
Microsoft.Maps.loadModule('Microsoft.Maps.Search', function () {
var searchManager = new Microsoft.Maps.Search.SearchManager(map);
var requestOptions = {
bounds: map.getBounds(),
where: data.address,
callback: function (answer, userData) {
map.setView({ bounds: answer.results[0].bestView });
var pushpin = new Microsoft.Maps.Pushpin(answer.results[0].location, {
icon: 'https://www.bingmapsportal.com/Content/images/poi_custom.png',
});
// map.entities.push(new Microsoft.Maps.Pushpin(answer.results[0].location));
map.entities.push(pushpin);
var infobox = new Microsoft.Maps.Infobox(answer.results[0].location, {
title: data.name,
description: data.address, visible: false,
actions: [
{ label: 'Handler1', eventHandler: function () { console.log('Handler1'); } },
{ label: 'Handler2', eventHandler: function () { console.log('Handler2'); } },
]
});
infobox.setMap(map);
Microsoft.Maps.Events.addHandler(pushpin, 'click', function () {
infobox.setOptions({ visible: true });
});
map.entities.push(pushpin);/**/
}
};
searchManager.geocode(requestOptions);
});
}
it runs smoothly and I have geocoded pushpins with infoboxes attached and showing up nicely.
But I am failing to figure out how to make all opened infoboxes close before opening new infobox on pushpin click event.
Please help..
I highly recommend creating a single infobox and reusing it as outline in this document: https://learn.microsoft.com/en-us/bingmaps/v8-web-control/map-control-concepts/infoboxes/multiple-pushpins-and-infoboxes

Code migration from tinymce 4 to tinymce 5 - problem with action function (true / false)

I have a problem with migrating the plugin from tinymce 4 to tinymka 5. The console tells me "Uncaught (in promise) TypeError: btn.active is not a function"
I can not find an equivalent for tinymce 5. Can someone replace it?
Code below:
tinymce.PluginManager.add('phonelink', function(editor, url) {
// Add a button that opens a window
var linkText = "";
var linkTitle = "";
var link = "";
// tinymce.DOM.loadCSS(url + '/css/phonelink.css');
editor.ui.registry.addButton('phonelink2', {
text: 'asddas',
icon: 'image-options',
onSetup: updateOnSelect,
onAction: onClickPhoneButton
});
// Adds a menu item to the tools menu
editor.ui.registry.addMenuItem('phonelink', {
text: 'asddas',
icon: 'image-options',
context: 'tools',
onAction: onClickPhoneButton,
onSetup: updateOnSelect
});
function onClickPhoneButton(){
editor.windowManager.open({
title: '123213123',
body: {
type: 'panel',
items: [
{type: 'input', name: 'phone', label: 'Teléfono', value: link},
{type: 'input', name: 'showtext', label: 'Texto a mostrar', value: linkText},
{type: 'input', name: 'title', label: 'Título', value: linkTitle}
]
},
buttons: [
{
text: 'Close',
type: 'cancel',
onclick: 'close'
},
{
type: 'submit',
name: 'submitButton',
text: 'Stwórz',
primary: true
}
],
onAction: function(e) {
alert('Toggle menu item clicked');
},
onSubmit: function(e) {
var data = e.getData();
var hrefLink = '<a title="' + data .title + '" href="tel:+34' + data .phone + '">' + data .showtext + '</a>';
if(link !== ''){
editor.setContent(hrefLink);
}else{
editor.insertContent(hrefLink);
}
e.close();
}
});
}
function updateOnSelect() {
var btn = this;
const editorEventCallback = function (e) {
var node = editor.selection.getNode();
var isTelLink = node.href !== undefined && node.href.indexOf('tel:+') !== -1
btn.active(isTelLink);
if(isTelLink){
link = node.href;
link = link.replace("tel:+34", "");
linkTitle = node.title;
linkText = node.text;
}
};
editor.on('NodeChange', editorEventCallback);
return function (btn) {
editor.off('NodeChange', editorEventCallback);
}
}
});
I searched the documentation for a replacement, but found nothing.
TinyMCE 5 no longer passes the button and menu instance via this. Instead it passes an API instance as the first parameter, so you'll want to change your updateOnSelect function to something like this:
function updateOnSelect(api) {
const editorEventCallback = function (e) {
var node = editor.selection.getNode();
var isTelLink = node.href !== undefined && node.href.indexOf('tel:+') !== -1
api.setActive(isTelLink);
if(isTelLink){
link = node.href;
link = link.replace("tel:+34", "");
linkTitle = node.title;
linkText = node.text;
}
};
editor.on('NodeChange', editorEventCallback);
return function (btn) {
editor.off('NodeChange', editorEventCallback);
}
}
You'll note var btn = this has been removed and that the API to set an item as active is setActive instead of active. This can be found in the documentation here: https://www.tiny.cloud/docs/ui-components/typesoftoolbarbuttons/#togglebutton and https://www.tiny.cloud/docs/ui-components/menuitems/#togglemenuitems (see the API section in both links).
In the above, you may have noticed both reference "Toggle" items. That's another change in TinyMCE 5, as different types of buttons/menu items have a separate registration API. So you'll also need to swap to using editor.ui.registry.addToggleButton and editor.ui.registry.addToggleMenuItem. More details about that can be found here if needed: https://www.tiny.cloud/docs/migration-from-4x/#customtoolbarbuttons
Here's an example fiddle showing the changes mentioned above: https://fiddle.tiny.cloud/B5haab.
Hopefully that helps!

How to add predefined places/markers to Leaflet Geocoder

I am using Leaflet Map with geocoder (ESRI) and Routing Machine.
I have added two markers, let's say my home and my work
var marker_work = L.marker([50.27, 19.03], { title: 'MyWork'}).addTo(map)
.bindPopup("work").openPopup();
var marker_home = L.marker([50.10, 18.4], { title: 'MyHome'}).addTo(map)
.bindPopup("home").openPopup();
Here is an example fiddle:
https://jsfiddle.net/21nmk8so/1/
How can I add this markers/point as a predefined places for ControlGeocoder?
I want to use them in search and use as a start point / end point for route calculation.
Another example for the same question: how to add custom-fake city with lat/lon and be able to search (find route) to/from that city.
I don't know if this is the best solution but it is working:
Create a custom Geocoder Class which overwrites the geocode function. There you can overwrite the result function and apply suggestions to the result.
L.CustomGeocoder = L.Control.Geocoder.Nominatim.extend({
suggestions: [],
setSuggestions(arr){
this.suggestions = arr;
},
createSuggestionFromMarker(marker){
this.suggestions.push({name: marker.options.title, center: marker.getLatLng()});
},
getResultsOfSuggestions(query){
var results = [];
this.suggestions.forEach((point)=>{
if(point.name.indexOf(query) > -1){
point.center = L.latLng(point.center);
point.bbox = point.center.toBounds(100);
results.push(point);
}
});
return results;
},
geocode(query, resultFnc, context) {
var that = this;
var callback = function(results){
var sugg = that.getResultsOfSuggestions(query);
resultFnc.call(this,sugg.concat(results));
}
L.Control.Geocoder.Nominatim.prototype.geocode.call(that,query, callback, context);
}
})
Then you have to use the new Geocoder Class:
var geocoder = new L.CustomGeocoder({});
var control = L.Routing.control({
waypoints: [],
router: new L.Routing.osrmv1({
language: 'en',
profile: 'car'
}),
geocoder: geocoder
}).addTo(map);
And finally you can add suggestions over markers and theier title option over createSuggestionFromMarker(marker) or setSuggestions(arr):
var suggestions = [
{
name: 'Test Car 1',
center: [50.27, 19.03]
},
{
name: 'Test Car 2',
center: [50.10, 18.4]
}
];
geocoder.setSuggestions(suggestions);
var marker_work = L.marker([50.27, 19.03], { title: 'MyWork'}).addTo(map);
var marker_home = L.marker([50.10, 18.4], { title: 'MyHome'}).addTo(map);
geocoder.createSuggestionFromMarker(marker_work);
geocoder.createSuggestionFromMarker(marker_home);
Update, use marker Ref instead of fix latlng
Change this two function, then the marker is referenced and it always searches from the current position of the marker:
createSuggestionFromMarker(marker){
this.suggestions.push({name: marker.options.title, marker: marker});
},
getResultsOfSuggestions(query){
var results = [];
this.suggestions.forEach((point)=>{
if(point.name.indexOf(query) > -1){
if(point.marker){
point.center = point.marker.getLatLng();
}
point.center = L.latLng(point.center);
point.bbox = point.center.toBounds(100);
results.push(point);
}
});
return results;
},
You can test this in the demo, when you drag the marker
https://jsfiddle.net/falkedesign/hu25jfd1/

Integrating WFS as gml in OL5

I try to visualize a WFS (from MapServer) in OL5.
The WFS works well (I can implement it without any problems in QGIS).
Also a request like:
http://blablabla/mapserv?service=WFS&version=1.1.0&request=GetFeature&typename=Flurstueckepunkt&srsname=EPSG:25832&bbox=411554,5791886,411677,5792008
gives me a nice gml-Output in epsg: 25832.
I try to implement it in OpenLayers like:
var vectorSource = new VectorSource({
format: new WFS(),
loader: function(extent, resolution, projection) {
var url = 'http://blablabla/mapserv?service=WFS&version=1.1.0&request=GetFeature&typename=ms:Flurstueckepunkt&srsname=EPSG:25832&bbox=412200,5791337,413600,5791800,EPSG:25832'
fetch(url).then(function(response) {
return response.text();
}).then(function(text) {
var features = vectorSource.getFormat().readFeatures(text);
// Add parsed features to vectorSource
vectorSource.addFeatures(features);
}).catch(function(error) {
alert(error.message);
})
}
});
var WFSLayer =new VectorLayer(
{
source: vectorSource,
projection: 'EPSG:25832',
style: new Style({ fill: new Fill({ color: 'yellow' })
})
});
var view = new View({
center: [rechtswert,hochwert],
zoom: mzoom,
projection: 'EPSG:25832'
});
var map = new Map({
layers: [osm,wmsLayer2,WFSLayer],
target: 'map',
view: view
});
...but the WFS-Layer is not shown at all.
Via the Mozialle-Debugger I can see, that the wfs-request workes, but nothing is visualized?
Has anybody an idea what is wrong here?
Allright, I got it. As the WFS ist delivering points the visualisation-style is important.
It workes now with:
var vectorSource = new Vector({
format: new GML3(),
loader: function(extent) {
var url = 'http://blablalbvlAn/cgi-bin/mapserv?service=WFS&version=1.1.0&request=GetFeature&typename=ms:Flurstueckepunkt&srsname=EPSG:25832&' +
'bbox='+ extent.join(',') +',EPSG:25832';
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
var onError = function() {
vectorSource.removeLoadedExtent(extent);
}
xhr.onerror = onError;
xhr.onload = function() {
if (xhr.status == 200) {
vectorSource.addFeatures(
vectorSource.getFormat().readFeatures(xhr.responseText));
var features3 = vectorSource.getFeatures();
} else {
onError();
}
}
xhr.send();
},
strategy: bbox
});
var WFSLayer =new VectorLayer(
{
source: vectorSource,
style: new Style({
image: new CircleStyle({
radius: 5,
fill: new Fill({
color: 'orange'
})
})
})
});

Extjs 4.0 MVC Add components to a form based on Store

I am ashamed to say I have spent most of today on this. I am trying to build a form based on the contents of an data store. I am using Ext.js and the MVC architecture. Here's what I have:
var myitems = Ext.create('Ext.data.Store', {
fields: ['name', 'prompt', 'type'],
data :
[
{"name":"name", "prompt":"Your name" , "type":"textfield"},
{"name":"addr", "prompt":"Your street address", "type":"textfield"},
{"name":"city", "prompt":"Your city" , "type":"textfield"}
]
});
function genwidget(name, prompt, type)
{
console.log("In genwidget with name=" + name + ", prompt=" + prompt + ", type=" + type + ".");
var widget = null;
if (type == "textfield")
{
// widget = Ext.create('Ext.form.field.Text',
widget = Ext.create('Ext.form.TextField',
{
xtype : 'textfield',
name : name,
fieldLabel: prompt,
labelWidth: 150,
width : 400, // includes labelWidth
allowBlank: false
});
}
else
{
// will code others later
console.log("Unrecongized type [" + type + '] in function mywidget');
}
return widget;
};
function genItems(myitems)
{
console.log("Begin genItems.");
var items = new Ext.util.MixedCollection();
var howMany = myitems.count();
console.log("There are " + howMany + " items.");
for (var i = 0; i < myitems.count(); i++)
{
var name = myitems.getAt(i).get('name');
var prompt = myitems.getAt(i).get('prompt');
var type = myitems.getAt(i).get('type');
var widget = genwidget(name, prompt, type) ;
items.add(widget);
console.log("items.toString(): " + items.toString());
}
return items;
};
Ext.define('MyApp.view.dynamicform.Form' ,{
extend: 'Ext.form.Panel',
alias : 'widget.dynamicformform',
// no store
title: 'Dynamic Form',
id: 'dynamicform.Form',
bodyPadding: 5,
autoScroll: true,
layout: 'auto',
defaults:
{
anchor: '100%'
},
dockedItems: [ ],
items: genItems(myitems),
// Reset and Submit buttons
buttons: [
{
text: 'Reset',
handler: function()
{
this.up('form').getForm().reset();
console.log('Reset not coded yet');
}
},
{
text: 'Submit',
formBind: true, //only enabled once the form is valid
disabled: true,
handler: function()
{
var form = this.up('form').getForm();
if (form.isValid())
{
form.submit({
success: function(form, action)
{
console.log('Success not coded yet');
}
});
}
}
} // end submit
], // end buttons
initComponent: function()
{
console.log("--> in dynamicform init");
this.callParent(arguments);
console.log("--> leaving dynamicform init");
}
}); // Ext.define
The error I am getting (I've had many throughout the day) is "my.items.push is not a function".
Thanks in advance for any help you can offer!
items is expected to be an array not MixedCollection. It is changed to MixedCollection later on if I remember good. So to fix your issue change:
var items = new Ext.util.MixedCollection();
// ...
items.add(widget);
to
var items = [];
// ...
items.push(widget);
Consider as well defining items of form as an empty array and then in initComponent make use of Ext.apply:
var me = this,
items = genItems(myitems);
Ext.apply(me, {
items:items
});