Leaflet Icon on multiple layer calling with ajax - ajax

i've a little issue for calling new icon with leaflet.
this is my code and i'm using the ajax lib leaflet-ajax.
var map = L.map('map').setView([51.505, -0.09], 13);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
var Icon1 = L.icon({
iconUrl: '/img/pin.svg',
iconSize: [38, 40]
});
var Icon2 = L.icon({
iconUrl: '/img/pin2.svg',
iconSize: [38, 40]
});
var Icon3 = L.icon({
iconUrl: '/img/pin3.svg',
iconSize: [38, 40]
});
function popUp(feature, layer) {layer.bindPopup('<p><b>' + feature.properties.name + '</b></p>' + '<p>' + feature.properties.description + '</p>');}
function popUp2(feature, layer) {layer.bindPopup('<p><b>' + feature.properties.name + '</b></p>' + '<p>' + feature.properties.special + '</p>');}
and where i think i have my issue with the call method for the icon
// call json
var geojsonLayer1 = new L.GeoJSON.AJAX("/json/jsonlayer1.json", {onEachFeature:popUp}, {icon:Icon1});
var geojsonLayer2 = new L.GeoJSON.AJAX("/json/jsonlayer2.json", {onEachFeature:popUp}, {icon:Icon2});
var geojsonLayer3 = new L.GeoJSON.AJAX("/json/jsonlayer3.json", {onEachFeature:popUp2}, {icon:Icon3});
// create group layer
var group1 = L.layerGroup([geojsonLayer1]);
var group2 = L.layerGroup([geojsonLayer2]);
var group3 = L.layerGroup([geojsonLayer3]);
// call group layer on dialog box
var checkboxesJson = {
"layer1": group1,
"layer2": group2,
"layer3": group3
};
L.control.layers(null,checkboxesJson).addTo(map);
Thank you for your help !

If my understanding is correct, you are trying to create a customized GeoJSON layer group through using leaflet-ajax plugin. But you do not know how to specify the icon that should be applied on markers for points of your GeoJSON data?
It looks like this plugin will simply use all standard L.GeoJSON options that are specified in the second argument of the constructor / factory, as you did for your onEachFeature option. Note that you can have many options in one single object.
However, you should use option pointToLayer instead of just icon, which is an option for a Marker. The function that you pass to pointToLayer should return an L.Marker, where indeed you would use the icon option.
For example you could do:
var geojsonLayer1 = L.geoJson.ajax(
"/json/jsonlayer1.json",
{
onEachFeature: popUp,
pointToLayer: function (feature, latlng) {
return L.marker(latlng, { icon: Icon1 })
}
});
Note that it is usually recommended to instantiate one icon per marker, even though it should work in your simple case.
By the way, note that L.geoJson (and with ajax plugin, L.geoJson.ajax) return an extended type of L.LayerGroup, so you do not have to import them into a new Layer Group to be able to use them in the Layers Control.
Therefore you could directly do:
// call group layer on dialog box
var checkboxesJson = {
"layer1": geojsonLayer1,
"layer2": geojsonLayer2,
"layer3": geojsonLayer3
};
L.control.layers(null,checkboxesJson).addTo(map);

Related

Dropdown menu with OpenLayers 3

I am using openlayers 3. From the values contained in a vector GeoJSON, I want to fill a dropdown menu. When selecting a value from the dropdown menu, I want to zoom in on the entity.
My problem now is that I want to generate my HTML from the attributes of my GeoJSON. So I tried this simple code but it doesn't work :
var menu = document.getElementById('menuDropDown');
vector2.getSource().forEachFeature(function() {
menu.innerHTML = feature.get('NOM').join(', ');
});
EDIT:
I'm able to populate a dropdown menu from a list:
var list = ['a','b','c'];
var mySelect = $('#mySelect');
$.each(list, function(val, text) {
mySelect.append(
$('<option></option>').val(val).html(text)
);
});
What i want to do it's to populate this list from the attribute of my vector
So i try this:
// vector2 it's a GeoJSON who is integrate on my map
vector2.getSource().getFeatures().forEachFeature(function(feature) {
list.push(feature.get('NOM'));
});
Firstly I'm assuming you have to pass some parameter to your callback:
vector2.getSource().forEachFeature(function(feature) {
Then you can append an item to a dropdown like so:
var item = document.createElement('option');
item.setAttribute('value', feature.get('NOM'));
var textNode = document.createTextNode(feature.get('NOM'));
item.appendChild(textNode)
menu.appendChild(item);
All together:
var menu = document.getElementById('menuDropDown');
vector2.getSource().forEachFeature(function(feature) {
var item = document.createElement('option');
item.setAttribute('value', feature.get('NOM'));
var textNode = document.createTextNode(feature.get('NOM'));
item.appendChild(textNode)
menu.appendChild(item);
});
I have resolve my problem:
vector2.getSource().on('change', function(evt){
var source = evt.target;
var list = [];
source.forEachFeature(function(feature) {
list.push(feature.get('NOM'));
});
// console.log("Ecrit moi les noms : " + list);
Thanks you to those who took the time to respond

Famo.us - triggering event and piping

Let's say I have three Views. AppView, MenuView and StripView. MenuView contains multiple StripViews and AppView contains one MenuView. How can I trigger event from StripView and listen on that event on AppView.
EDIT
Let's say I want to click on ImageSurface on StripView and reigster that event on AppView, and then do some transitionig.
MY SOLUTION
Everything is based on Timbre app, created in Famou.us Starter Kit Reference Tutorials
// StripView.js (_setListeners() is called in StripView constructor and bodySurface is defined in code)
function _setListeners() {
var eventScope = this._eventOutput;
this.backgroundSurface.on('click',function(){
eventScope.emit('test', { somedata:'some value'} );
}.bind(this));
}
// MenuView.js (_createStripViews() is called in MenuView constructor)
function _createStripViews() {
this.stripModifiers = [];
var yOffset = this.options.topOffset;
for (var i = 0; i < this.options.stripData.length; i++) {
var stripView = new StripView({
iconUrl: this.options.stripData[i].iconUrl,
title: this.options.stripData[i].title
});
var stripModifier = new StateModifier({
transform: Transform.translate(0, yOffset, 0)
});
this.stripModifiers.push(stripModifier);
this.add(stripModifier).add(stripView);
yOffset += this.options.stripOffset;
stripView.pipe(this._eventOutput);
}
}
//AppView.js (menuView is defined in code and _setListeners() is called in AppView constructor)
function _setListeners() {
this.menuView.on('test',function(){
console.log("IT WORKS");
}.bind(this));
}
You want to use Views built in handlers to achieve this. These are _eventInput and _eventOutput.. Here is an example using an ImageSurface in StripView and responding to a click in AppView..
Hope it helps!
// In StripView.js
var imageSurface = new ImageSurface();
imageSurface.on('click',function(){
this._eventOutput.trigger('image-click', { somedata:'some value'} );
}.bind(this));
// In AppView.js
var stripView = new StripView();
this.subscribe(stripView);
this._eventInput.on('image-click',function(data){
// Do Something
});

Infinite Scrolling with wookmark plugins scrolling

With ref. to above subject, I am using wookmark plugin to scroll our home page data dynamically….I have studied the tutorial provided on wookmark and I m using the exact script provided by wookmark and working fine shorts of not 100% working.
Things it stucks when it reaches at bottom of the window then we slightly press the up arrow key, that loads the products again and this is happens randomly some time it scrolls perfectly and some time it stucks and if presses up arrow key it starts working again.
Kindly help me out where I m going wrong. Kindly provide me the easy working script for the same.
I m using following code :
(function ($) {
$('#main').imagesLoaded(function () {
var handler = null;
// Prepare layout options.
var options = {
itemWidth: 200, // Optional min width of a grid item
autoResize: true, // This will auto-update the layout when the browser window is resized.
container: $('#main'), // Optional, used for some extra CSS styling
offset: 20, // Optional, the distance between grid items
outerOffset: 20, // Optional the distance from grid to parent
flexibleWidth: 300 // Optional, the maximum width of a grid item
};
function applyLayout() {
$('#main').imagesLoaded(function () {
// Destroy the old handler
if (handler.wookmarkInstance) {
handler.wookmarkInstance.clear();
}
// Create a new layout handler.
handler = $('#display li');
handler.wookmark(options);
});
handler.wookmark(options);
}
/**
* When scrolled all the way to the bottom, add more tiles.
*/
function onScroll(event) {
// Check if we're within 100 pixels of the bottom edge of the broser window.
var winHeight = window.innerHeight ? window.innerHeight : $(window).height(); // iphone fix
//var closeToBottom = ($(window).scrollTop() >= $((document)).height() - $((window)).height() - $("#footer").height() - 500); //(($(window).scrollTop() - 100)); //+ "%"
var closeToBottom = ($(window).scrollTop() + winHeight > $(document).height() - 100);
if (closeToBottom) {
// Get the first then items from the grid, clone them, and add them to the bottom of the grid.
var items = $('#display li'),
firstTen = items.slice(0, 10);
//$('#display').append(firstTen.clone());
applyLayout();
}
};
// Capture scroll event.
$(window).bind('scroll', onScroll);
// Call the layout function.
handler = $('#display li');
handler.wookmark(options);
});
$(window).load(function () {
handler.wookmark(options);
});
})(jQuery);
If you commented out
//$('#display').append(firstTen.clone());
then the new items will not be loaded on the end of list. You need to uncomment that line to get new items.
In real life instead of
var items = $('#display li'),
firstTen = items.slice(0, 10);
$('#display').append(firstTen.clone());
you would need a code that will load new items.
Also I think it might make sense to change > to >=
var closeToBottom = ($(window).scrollTop() + winHeight >= $(document).height() - 100);
to load new items if scroll position is more or equal to the height of window - 100, where 100 is just some value - you could try 200 or even more to see if it will work better for you.

set an id at "Raphaeljs set"

i want to set an id to Raphael set because i want to display it after an event click.
this is my set:
var divResult = document.getElementById('printResult');
var space2Draw = Raphael(divResult, 1600, 900);
var st = space2Draw.set();
st.push(
space2Draw.circle(newXCoordinates, newYCoordinates, 20).click((function (valore) {
return function () {
window.open("index-point.html?id=" + (valore) + "&type=" + type + "&description=" + description + "&name=" + name);
}
}(valore))).mouseover(function () {
this.attr({ 'cursor': 'pointer' });
this.attr({ 'opacity': '.50' });
}).mouseout(function () {
this.attr({ 'opacity': '1' });
})
);
in my page i have a button:
function show(){
var element = space2Draw.getById(-1);
element.show();
}
}
Is not possible to set an id in this way : set.id = -1?
How can I set an id and then I find the set?
Thanks in advance for the help.
You can try using setAttribute() to add a CLASS for the elements you want to access later, and then modify their CSS propperties. The first step would be to change the CLASS of each element:
myElement.node.setAttribute("class", "class_name");
Unfortunately, Raphael does not allow you to handle sets as unique HTML objects, so you cannot do this for the entire set at once. Instead, you might have to do this for each element in your set, possibly with a for cycle, something like this:
for (var i=0; i<st.length; i++) {
st[i].node.setAttribute("class", "class_name");
}
Then, using JQuery, you can modify the CSS properties of the CLASS you created in order to display the elements in your set.
function show(){
$('.class_name').css('display', 'block');
}
I hope this helps.
Maybe you can use Raphael data() function to assign any data to your element/set.
Example:
// you can keep global var for your id and increment it within your code
var id = 0;
var p = Raphael(100, 100, 500, 500),
r = p.rect(150, 150, 80, 40, 5).attr({fill: 'red'}),
c = p.circle(200, 200, 70).attr({fill: 'blue'});
var set = p.set(r,c).data("id", id);
id++;
// then in your click event to get the id you can do
var whichSet = this.data("id");
// data("id") will return you the global id variable
Good Luck

Store & retrieve the identifiers of a multipliable widget's instances

The aim is to remove only the last row at any time and only by the last remove button.
There is a user interface which building up as a multiplication of the same row. The number of rows are controlled by 'Add' & 'Remove' buttons which are also elements of the row. The problem is that the hidden widgets - that are applied for each row to distinguish the instances by storing their row numbers - are storing the very same number which is the last one. Except the first (0) hidden widget which stores the proper number (0). Where am I missing the point? How should this be resolved?
As per the remove buttons have two different purposes (not detailed here), we use a cacheService to distinguish the last row from all the others. Only the last row should be removed at any time.
var cache = CacheService.getPrivateCache();
we clear the cache and create the first instance
function doGet() {
var app = UiApp.createApplication();
app.add(app.createVerticalPanel().setId('mainContainer'));
cache.removeAll([]);
ui(0);
cache.put('numberOfInstances',0);
return app; }
each instance is held by a horizontal panel which contains the mentioned hidden widget, a label which informs about the instance number, and the Add & Remove buttons.
function ui(instance) {
var app = UiApp.getActiveApplication();
var eventContainer = app.createHorizontalPanel()
.setId('eventContainer' + instance);
var instanceContainer = app.createHidden('instanceContainer',instance);
var showInstance = app.createLabel(instance)
.setId('showInstance' + instance);
var addButton = app.createButton('Add')
.setId('add' + instance)
.addClickHandler(app.createClientHandler()
.forEventSource().setEnabled(false)) //avoiding multiple click during server response
.addClickHandler(app.createServerHandler('add')
.addCallbackElement(instanceContainer));
var removeButton = app.createButton('X')
.addClickHandler(app.createServerHandler('remove')
.addCallbackElement(instanceContainer));
app.getElementById('mainContainer')
.add(eventContainer
.add(instanceContainer)
.add(showInstance)
.add(addButton)
.add(removeButton));
return app; }
and the event handling...
function add(inst) {
var app = UiApp.getActiveApplication();
var instance = Number(inst.parameter.instanceContainer);
ui(instance+1);
cache.put('numberOfInstances',instance+1);
return app; }
function remove(inst) {
var app = UiApp.getActiveApplication();
var instance = Number(inst.parameter.instanceContainer);
var numberOfInstances = cache.get('numberOfInstances')
if( (instance != 0) && (instance = numberOfInstances) ) {
app.getElementById('mainContainer').remove(app.getElementById('eventContainer' + instance));
cache.put('numberOfInstances',instance-1);
app.getElementById('add' + (instance-1)).setEnabled(true); } //avoiding multiple click during server response
return app; }
The aim is to remove only the last row at any time and only by the last remove button.
Many Thanks.
Why don't you simply use a clientHandler just as you did on the 'add' button? You could target the preceding 'remove' button and disable it each time you create a new one and change /update each time you remove one row.
EDIT : I can suggest you something, feel free to have a look, I changed a bit the approach but it is working and I hope you'll find it at least interesting ;-)
Link to the online test
function doGet() {
var app = UiApp.createApplication();
var counter = app.createHidden().setName('counter').setId('counter').setValue('1');
var mainContainer = app.createVerticalPanel().setId('mainContainer')
app.add(mainContainer.add(counter));
var event1Container = app.createHorizontalPanel()
var showInstance = app.createLabel('1')
var addButton = app.createButton('Add')
.setId('add1')
.addClickHandler(app.createClientHandler()
.forEventSource().setEnabled(false)) //avoiding multiple click during server response
.addClickHandler(app.createServerHandler('add')
.addCallbackElement(mainContainer));
var removeButton = app.createButton('X')
.setId('remove1')
.addClickHandler(app.createServerHandler('remove')
.addCallbackElement(mainContainer));
mainContainer.add(event1Container
.add(showInstance)
.add(addButton)
.add(removeButton));
return app; }
function add(inst) {
var app = UiApp.getActiveApplication();
var hiddenVal =inst.parameter.counter;
var counterVal = Number(hiddenVal);
var mainContainer = app.getElementById('mainContainer')
var counter = app.getElementById('counter')
++ counterVal
counter.setValue(counterVal.toString())
var eventContainer = app.createHorizontalPanel().setId('eventContainer'+counterVal)
var showInstance = app.createLabel(counterVal.toString())
var addButton = app.createButton('Add')
.setId('add'+counterVal)
.addClickHandler(app.createClientHandler()
.forEventSource().setEnabled(false)) //avoiding multiple click during server response
.addClickHandler(app.createServerHandler('add')
.addCallbackElement(mainContainer));
var removeButton = app.createButton('X')
.setId('remove'+counterVal)
.addClickHandler(app.createServerHandler('remove')
.addCallbackElement(mainContainer));
app.add(eventContainer
.add(showInstance)
.add(addButton)
.add(removeButton));
if(counterVal>1){app.getElementById('remove'+(counterVal-1)).setEnabled(false)}
return app; }
function remove(inst) {
var app = UiApp.getActiveApplication();
var counterVal = Number(inst.parameter.counter);
var counter = app.getElementById('counter')
if(counterVal ==1) {return app}
var maincontainer = app.getElementById('mainContainer')
app.getElementById('eventContainer' + counterVal).setVisible(false)
--counterVal
counter.setValue(counterVal.toString())
app.getElementById('add'+counterVal).setEnabled(true)
app.getElementById('remove'+counterVal).setEnabled(true)
return app;
}
NOTE : I didn't make use of .remove(widget) since this is a fairly new method and I don't know exactly how it works... I'll test it later. Until then I used setVisible(false) instead, sorry about that :-)
Note 2 : I didn't use the cache since the hidden widget is sufficient to keep track of what is going on... if you needed it for something else then you could always add it back .

Resources