Append Key/Value pair to L.Control.layer in Leaflet - javascript

Here is a simplified example of my "issue."
I have a list of key/value pairs like this:
var baseMaps = {"thing1": thing1,
"thing2": thing2};
var overlayMaps = {"OverLay1": link to overlay2
"Overlay2": link to overlay2};
etc...........
I can uses this code to add on to my object list:
overlayMaps["New Item"] = link to new item;
I verify on the console that it's added to the overlayMaps list.
Issue: It does not show up in the box on the side of the map like all the other ones. They are in a box with little check marks by them to turn them on and off. Am I missing some code to do this? It seems like I need a way to refresh the layer group list.

Assuming the rest of your code is as per the example in documentation.
L.control.layers(baseLayers, overlays).addTo(map);
The problem is you've lost reference to the control instance because didn't assign it to anything. Since the addTo method is chainable it will give you the control.
var layerControl = L.control.layers(baseLayers, overlays).addTo(map);
Now you can access it in your code and run its methods like layerControl.addBaseLayer

Related

How do I split/slice a leaflet L.layerGroup into mutliple L.layerGroup(s)?

I'm using leafletjs to draw a line from marker to marker. But the markers are grouped into sets, each with its own name. I get the data from MySQL with PHP and create;
var OBJMarkerList = L.layerGroup([W0DLK01,W0DLK02,W0DLK03,W0DLK04,W0DLK05,WA0TJT01,WA0TJT02,WA0TJT03,WA0TJT04,WA0TJT05,WA0TJT06,WA0TJT07,WA0TJT08,WA0TJT09,]);
Notice the name changes.
But I need to pass it into a function one part at a time in order to change the color of the line. So while I have the above OBJMarkerList what I really need is;
var W0DLKOBJMarkerList = L.layerGroup([W0DLK01,W0DLK02,W0DLK03,W0DLK04,W0DLK05,]);
And another for the other set of values, WA0TJTOBJMarkerList.
I created an array of the names;
const allnameBounds = (['W0DLKOBJMarkerList','WA0TJTOBJMarkerList']);
But its literally just the names and the function (below) will not accept it as input to convert to the x,y coordinates I need.
function connectTheDots(data){
var c = [];
for(i in data._layers) {
var x = data._layers[i]._latlng.lat;
var y = data._layers[i]._latlng.lng;
c.push([x, y]);
}
return c;
}
How can I split the L.layerGroup into two or any number of parts based on the variable names given? There will usually be more than just two, this is a simplified example.
I tried iterating over the allnameBounds array in all the usual ways and while the looping works to extract the name, the function does not process it like the leaflet object it is.
I also went back to the MySQL/PHP and tried to create a stand alone for each name, that's fine but I still need another list of the L.layerGroup names to iterate over.
Spliting or slicing the combined seemed the only answer. I just don't know how to get there.
Can someone give me a better way or show me how to split the overall list?

Leaflet Maps: How to create an overlay with key/value pairs using the contents from an array?

In my project, when I load a page I pull a list of overlay names from the database, these are stored in a JS Array.
Using the default code below, how do I fill the overlayMaps with contents from an array rather than hard coding what the values will be:
var overlayMaps = {
"Cities": cities,
"Towns": towns
};
So as an example, instead of creating overlayMaps with the hard coded values Cities & Towns, I need to pull these values from an array that gets its data from the DB, The array in leymans terms might look like this under the hood:
[ "MyValue1": myvalue1,"MyValue2": myvalue2, "MyValue2": myvalue2,] etc
Maybe I need to create a dictionary, although I have no experience doing this in JS, only in C#
Am using guide: https://leafletjs.com/examples/layers-control/
Solution:
Reading the leaflet API instructions, you can actually add a single item to an L.control
one at a time using the command addOverlay( layer, name). Adds an overlay (checkbox entry) with the given name to the control. For demo purposes below, I'm using the same value var cities for each of the three checkboxes, but to show how we add the individual items from the array, we're looping through this array and adding the items one at a time.
var littleton = L.marker([39.61, -105.02]).bindPopup('This is Littleton, CO.'),
denver = L.marker([39.74, -104.99]).bindPopup('This is Denver, CO.'),
aurora = L.marker([39.73, -104.8]).bindPopup('This is Aurora, CO.'),
golden = L.marker([39.77, -105.23]).bindPopup('This is Golden, CO.');
var cities = L.layerGroup([littleton, denver, aurora, golden]);
var places = new Array()
places.push("Cities");
places.push("Towns");
places.push("MyPlaces");
var lControl = L.control.layers(null, null);
lControl.addTo(map);
places.forEach(myFunction);
function myFunction (item) {
lControl.addOverlay(cities, '' + item + '');
}

knockout js, add new item to an array

So this follows on from my previous question:
knockout js, add additional elements to an array
Basically I have an app where a user fills in certain data, clicks next and this is added to an array. However, what I'd like to do is add some items into the array before the user even begins using the app (these items I get from a database). The idea being that at the start they can view each item in the array and then choose and an item and edit this item. I've got a feeling I'm missing something blindingly obvious but I cannot seem to figure it out
Knockout observable arrays have equivalent functions to native JavaScript arrays. See: http://knockoutjs.com/documentation/observableArrays.html
So you need just to use arr.pop(item) or arr.push(item).
In case you need to replace all items and want to avoid multiple events to raise, use observableArray.valueWillMutate() and valueHasMutated() functions. See sample where I do swap the entire array:
ko.observableArray.fn.replaceWith = function (valuesToPush) {
// NOTE: base on - ko.observableArray.fn.pushAll
var underlyingArray = this();
var oldItemcount = underlyingArray.length;
this.valueWillMutate();
// adding new items to obs. array
ko.utils.arrayPushAll(underlyingArray, valuesToPush);
// removing old items (using KO observablearray fnc.)
if (oldItemcount > 0)
this.removeAll(underlyingArray.slice(0, oldItemcount));
this.valueHasMutated();
return this; //optional
};

How to add new key/value pair element to an existing array?

var onHomePageLoaded = function(retMsg)
{
$scope.data = retMsg.data.records;
$scope.data.link : 'http://www.newwebsite.com'
}
After i have added link element (key/value) to the javascript object, i am not able to get the same in the HTML template
<div ng-repeat="record in data">
<a ng-href="{{record.link}}"> Click Here </a>
</div>
Javascript is a dynamic language. You can add properties to existing objects in a very simple way , like assigning a value to an existing property. Just add a new property
$scope.data.link = 'http://www.newwebsite.com'
if retMsg.data.records is an array, still you can add a property to $scope.data.
if you want different link for every object in array then, do this.
$scope.data.forEach(function(obj){
obj.link = "your custom link" // write your logic here to produce different link.
});
If data is an array you can use
$scope.data.push(yourData);
for example
$scope.data.push({link : 'http://www.newwebsite.com'});
Or if you want to access the objects inside the array and add them a key value pair you can do as follow:
// add the link to the first entry
$scope.data[0].link = 'http://www.newwebsite.com';
Sorry. Do not know if I understood well.
Maybe you can define scope.data as:
$scope.data = {retMsg.data.records}
Then for example a function:
$scope.addNew = funtion(){
$scope.data.newElement = $scope.viewElement
};
In your HTML
<label>{{data}}</label> // Which makes reference to the $scope.data at the controller
<input ng-change="addNew()" ng-model="viewElement"></input>
<label>{{data.newElement}} // Will be empty at the very beginning but will show the new element once it is created.
Hope it helps
I see several issues with your code.
First, you use the variable name record in your ng-repeat, but then use report in ng-href. I assume those should be the same.
Also, link isn't a member of record, it is a member of data. You set it as a member of data here: $scope.data.link : 'http://www.newwebsite.com'. If you want to add that link to each record, in your onHomePageLoaded function, you'll need to loop through all the records you add to data, and add the link property to each one.

Working with Data Attributes - Build a List & See if One Exists

I have 2 questions based on the graphic below:
How can I tell if one of the 'data-conversationmessageuserid' data attributes with a specific value exists - say 1000000003? I believe data selectors is what I need and have tried the following but its not working yet:
if($('#conversationsInBoxMessagesWrapperDIV')['data-conversationmessageuserid=1000000003']) {
// do something
}
How could I get all the 'data-conversationmessageuserid' data attributes into an array and the loop through them? I'm still playing with this code but its far from publishable. Trying to use .map
.map(function()
thankyou so much
Try:
if($('#conversationsInBoxMessagesWrapperDIV [data-conversationmessageuserid=1000000003]').length)
or
$('#conversationsInBoxMessagesWrapperDIV').find('[data-conversationmessageuserid=1000000003]') //Or children only to look at one level.
To get all the data values you could do:
var conversationmessageuserids = $('#conversationsInBoxMessagesWrapperDIV').children().map(function(){
return $(this).data('conversationmessageuserid');
}).get();
jQuery supports data attributes: http://api.jquery.com/data/
So you could do if($('#conversationsInBoxMessagesWrapperDIV').data('conversationmessageuserid') === 1000000003)

Categories