ESRI Javascript API: Looping to Build a Layer Selection Menu - javascript

For reference, please see this: https://developers.arcgis.com/javascript/jssamples/map_dynamiclayerlist.html
But, unlike the ESRI example, I am loading several different Services and each Service has multiple Layers. So I have modified the ESRI code per the following:
var visible = [];
function buildLayerList() {
arrayUtils.forEach(map.layerIds, function (id) {
var currLayer = map.getLayer(id);
var items = arrayUtils.map(currLayer.layerInfos, function (info, index) {
if (info.defaultVisibility) {
visible.push(info.id);
}
return "<input type='checkbox' class='list_item'" + (info.defaultVisibility ? "checked=checked" : "") + "' id='" + info.id + "'' /><label for='" + info.id + "'>" + info.name + "</label>";
});
});
//more code per ESRI
}
But, in my case, the items variable is not getting any values; it is returning as null or not defined. I presume that is because I have basically two loops, unlike ESRI's.
So how do I fix it? I would hate to hard-code the layer selection menu option but may have to if I cant figure this out.
Note: These are all Arcgis Dynamic Layers.
Thanks!

Never mind: All I needed was a Esri Javascript API's 'TOC Widget'; I downloaded that and implemented in my code. Much easier than trying to re-invent the wheel.
Thanks--especially to #Pointy.

Related

Can't sort a list by datasets when actively trying to change dataset values

I'm writing an application in C# with Cefsharp. I'm utilizing C#, JavaScript and HTML/CSS for this project.
I recently posted a question about issues with sorting a list based on the innerHTML text of the said item (the text included the index of the list item) in the list. I received help with this, however the demands changed a bit and I can no longer have the index number in the actual text.
I managed to solve this by using datasets in HTML instead. I was having issues making the list sort but I was sure that it technically should work so I isolated everything in jsfiddle. Everything worked perfectly, so I decided to add a few of the elements in my function at a time.
I found out that the sorting stops working because I'm trying to change the values of my datasets. The actual value of the datasets are succesfully changing, however the sorting stops working for some reason. If I'm NOT trying to change the values of the datasets, it works perfectly. These are the relevant codes:
WinForms function (redacted, executed every 1000ms):
private async void timer1_Tick(object sender, EventArgs e)
{
foreach (var order in orderResult.OrderResult.Select((value, i) => (value, i)))
{
chromeBrowser.ExecuteScriptAsync("updateOrderQueue", order.i, order.value.Reference, order.value.PickedUpAt == "" ? "📤" : order.value.PickedUpAt,
order.value.DeliveredTo == "" ? "📥" : order.value.DeliveredTo, order.value.RobotId.Length > 0 ? order.value.RobotId.Remove(0, 4) : order.value.RobotId,
order.value.StatusCode, status.GetOrderStatus(order.value.StatusCode));
}
}
JavaScript functions:
function updateOrderQueue(index, reference, pickedup, deliveredto, robotId, statuscode, statustext) {
var list = $('ul#orderQueueList');
var count = $("ul#orderQueueList li").length;
var item = jQuery("#order" + jq(reference));
var robotQueue = jQuery("#robotQueue" + jq(reference))
if (!document.getElementById('order' + reference) && statuscode < 4 && count < 9) {
var data = $(`<li data-indexn="` + index + `" class="list-group-item list-group-item-secondary d-flex justify-content-between align-items-center border border-dark" id="order` + reference + `">
<h3 class="mt-1" id="text`+ reference + `">
`+ index + `) ` + pickedup + ` âž” ` + deliveredto + ` (` + statustext + `)
</h3>
<small class="badge badge-dark rounded" style="font-size:24px;" id="robotQueue`+ reference + `">` + robotId + `</small>
</li>`);
data.appendTo(list).hide().fadeIn(500);
} else {
var locations = jQuery("#text" + jq(reference));
var assignedrobot = jQuery("#robotQueue" + jq(reference));
locations.text(index + ') ' + pickedup + ' âž” ' + deliveredto + ' (' + statustext + ')');
assignedrobot.text(robotId);
}
item.attr("data-indexn", index);
sortList();
}
function sortList() {
$("#orderQueueList li").sort(function (a, b) {
return parseInt($(a).data('indexn')) - parseInt($(b).data('indexn'));
}).appendTo('#orderQueueList');
}
When this code is removed from my JavaScript function, everything works as intended:
item.attr("data-indexn", index);
This is the list in the HTML code:
<ul id="robotQueue">
<li id="order######" data-indexn="0">
TEXT
</li>
</ul>
I've tried to isolate as much as I can to try and find what causes it but I can't figure it out. Sorry if the post is a bit long.
Thanks!
Alright, so I'm not sure if this actually counts as an answer or not. According to everything I've been reading, the use of the attr() method should work perfectly fine to set values for datasets (which is what I tried to do). It does succesfully set new values for each item but it also messes with the sorting for some reason, making it not work anymore.
Couldn't find any reason as to why this would not work however I tried setting the values with the data() method instead, example below:
function updateDataset() {
var item = $("#order");
item.data("indexn", value); // "data-indexn" in HTML would be only "indexn" here
}
This worked perfectly fine and the code now runs without any issues.
Again, I'm not sure why attr() did not work and there might be a better answer for this question but I'm posting this here in case someone else has a similar problem.

How do I encode/decode a fetch URL/JSON using javascript and flask

This is in reference to dynamically change options in a list by another list. Unfortunately, it all works except if the project name has a " or a #. Eg. Project name: '10" Centerline #3 Pipe'
I am a newbie to this and I have been cut/paste (learning) as I go along. If someone can help, it will be great. I am seen some things about escaping and encoding URI stuff but not sure where to put it in. The other problem is just understanding what happens past the onchange event.
I can get the list of project names from a previous list and it shows up in my HTML page. However, when I select the choices that have a ( " ) or a ( # ), the next populated list breaks.
Thanks in advance. I really, really appreciate the time if someone puts in a response.
Here is the javascript portion:
project_name_select.onchange = function(){
project_name = project_name_select.value;
fetch('/sr/new/project/' + project_name).then(function(response){
response.json().then(function(data) {
var areaHTML = '<option value="See List">Select Area</option>';
for (var state of data.project_area) {
areaHTML += '<option value="' + state.project_area + '">' + state.project_area + '</option>'
}
project_area_select.innerHTML = areaHTML;
});
});
}
Here is the flask portion:
#surveys.route("/sr/new/project/<get_project_name>")
def project(get_project_name):
project_dict, dict_type = choice_project_dict(get_project_name)
project_areaArray = []
for proj in project_dict:
ownerObj = {}
ownerObj['id'] = proj['company_name']
ownerObj['owner_company'] = proj['company_name']
ownerArray.append(ownerObj)
return jsonify({'project_area': project_areaArray})

How to pull a random row from google sheets and use it in an HTML table

I'm working on a small project where I am wanting to randomly pull one row of a google sheet, and then use that data in an HTML table.
For now, my solution has been first to use javascript to make a random number, then generate an HTML table from google sheets for just that row using this method. So, I end up with a URL for an HTML table with just header row, and a random row of data, similar to this. Then I just embed that table as an object in my HTML page. This is the gist of it:
< script >
window.onload = function() {
var albumno = Math.random() * 408;
var albumno = Math.round(albumno);
var albumurl = "https://docs.google.com/spreadsheets/d/UNIQUE-DOCUMENT-ID/gviz/tq?tqx=out:html&tq=SELECT%20B%2C%20D%2C%20E%2C%20F%2C%20G%20WHERE%20A%20MATCHES%20%27" + albumno + "%27&gid=1739065700";
document.getElementById("output").innerHTML = "ALBUM NUMBER: " + albumno + ".";
document.getElementById("albumpath").innerHTML = '<object align="middle" data="' + albumurl + '">';
};
</script>
There are two major drawbacks. First, the table cannot be (easily) formatted when embedded as an object. Second, my google sheet is a list that is added to weekly, and therefore I have to manually adjust the limits of the random value generated in my javascript.
Is there a way to do this more effectively in Javascript? Perhaps by scraping the full table, and then randomly selecting a row of data, which can be used in an proper HTML table (i.e. not embedded as an object)? Or maybe there exists a google sheets API that would help me?
UPDATE:
I have managed to write a quick function in Google Apps Script that picks the random row of data. I have figured two ways to output the data, option 1 as an array, or option 2 as HTML code for a table. Now how do I call this function in my HTML page, and make use of these data?
}
function randomalbum() {
//get spreadsheet
var ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/[DOCID]/edit#gid=1');
var sh = ss.getSheetByName("Pick List");
//find last album
var Fvals = sh.getRange("F:F").getValues();
var Flast = Fvals.filter(String).length;
var colnum = sh.getRange(2, 1, Flast).getValues();
var albumlast = Math.max.apply(null, colnum)-1;
//pick random row (note the row an album is in is 1 more than the album no.)
var rowrand = Math.round(Math.random()*(albumlast+1));
//extract data of interest
var albumrand = rowrand -1;
var pick = sh.getRange(rowrand, 5).getValues();
var artist = sh.getRange(rowrand, 6).getValues();
var title = sh.getRange(rowrand, 7).getValues();
//make array (option 1)
var array = [albumrand, pick, artist, title];
return array;
//make HTML string (option 2)
var HTMLString = " <table style='width:100%'>"
+ "<tr>"
+ "<th>Album No.</th>"
+ "<th>Picked By</th>"
+ "<th>Artist</th>"
+ "<th>Artist</th>"
+ "</tr>"
+ "<tr>"
+ "<td>" + albumrand + "</td>"
+ "<td>" + pick + "</td>"
+ "<td>" + artist + "</td>"
+ "<td>" + title + "</td>"
+ "</tr>"
+"</table>"
HTMLOutput = HtmlService.createHtmlOutput(HTMLString);
return HTMLOutput
}
Using a Google Sheets API without needing to run your own server: I remember following the suggestions in the following article to solve this a while ago.
https://coderwall.com/p/duapqq/use-a-google-spreadsheet-as-your-json-backend
You'll probably need another service to add CORS headers to the Google response because cors.io apparently no longer exists.
If you want to publish a web app out of the HTMLOutput returned by your function, you can do the following:
Rename your function to doGet: if you do this, Apps Script will run this function whenever a user visits the URL of the web app you are about to publish, as you can see here.
Remove the return array; in your code: the keyword return finishes current function, so the code will never return an HTMLOutput, and an array of values is not a valid object to return in this situation.
Publish the script as a web app: in your script editor, select Publish > Deploy as web app. Then select a Project version, choose under whose authorization the app should run and who should have access to it, and click Deploy. A URL will show app as Current web app URL. If you access that URL, you will see the HTML you created.
I hope this is of any help.

Trying to get strings from specific sites (same domain) and place them in a chart

I have a chrome extension that, right now, is purely a cosmetic addition to a Counter-Strike forum and matchmaking site. I'm trying to implement some Javascript to show players ranks when looking at the statistics of a match. Currently, it looks like this: statistics page imgur
I'm trying to add a new column to the left of where players' names appear that shows their ranks. Ranks are currently only stored on the players' profile page, so I'm trying to write code that will go to each players' profile (currently hyperlinked to their name), get their rank and display that as text.
I have 0 understanding of Javascript despite trying to learn it many times but this is a heavily requested feature and I'd like to implement it for my users.
sample statistics page
sample profile page
As of a few months ago, the following code worked:
function findRanks(i) {
var allUsers = $(document).find("#body-match-total" + i + " tr");
$.each($(document).find("#body-match-total" + i + " tr"), function(index, value){
var userLink = "https://play.esea.net/users/" + allUsers[index].children[0].children[1].innerHTML
$.get(userLink, function(data) {
var parsed = $('<div/>').append(data);
rank = $(parsed).find("#rankGraph h1").text();
allUsers[index].children[0].children[1].innerHTML += " (" + rank + ") ";
});
});
}
findRanks(1);
findRanks(2)
Was missing a bracket. Thanks to some random guy on ESEA forums for the help.
Here is the functional code for people with the same issue
function findRanks(i) {
var allUsers = $(document).find("#body-match-total" + i + " tr");
$.each($(document).find("#body-match-total" + i + " tr"), function(index, value){
var userLink = "https://play.esea.net/users/" + allUsers[index].children[0].children[1].innerHTML
$.get(userLink, function(data) {
data = data.replace(/<img[^>]*>/g,"");
var parsed = $('<div/>').append(data);
rank = $(parsed).find("#rankGraph h1").text();
allUsers[index].children[0].children[1].innerHTML += " (" + rank + ") ";
});
});
}
findRanks(1);
findRanks(2);

term_exists not working in Javascript

I finally got my back-end to create the wheel codes from the checked taxonomies in the add custom post admin area.
Now, I want to add that tire code to the wheel_type taxonomy.
The below code ran great, until I added the if statement under //Add code to Taxonomy
Now nothing is working, but I get nothing in the error console.
I figure it must be a stupid syntax mistake - can anyone help me out?
Or am I missing something else?
jQuery('#replace').click(function(){
//get tire code and name
var code = jQuery('input[name="tire_code"]').val();
var name = jQuery('input[name="tire_name"]').val();
var bname = jQuery('input[name="tire_bname"]').val();
alert(code + " + " + name + " + " + bname);
//get tire brand
var tirebran = jQuery('#tire_brandchecklist').find(":checked").parent('label').text();
tirebran = jQuery.trim( tirebran );
//Add code to Taxonomy
if( term_exists( code, wheel_type ){
continue;
}
else
{
wp_insert_term( code, wheel_type );
}
//update title
var title = code + ' : ' + name + ' tires';
if(tirebran!=''){
title += ' with ' + bname + ' letters';
}
jQuery('input[name="post_title"]').focus().val(title);
});
//-->
</script>
unless i've misunderstood your question, you're trying to call wordpress methods via javascript.
term_exists() and wp_insert_term() are PHP methods within the wordpress code, not accessible directly via Javascript (unless you have written interfaces to them).
continue doesn't make any sense there; just check for !term_exists... and call wp_insert_term when it doesn't exist.
if (!term_exists(code, wheel_type)) {
wp_insert_term(code, wheel_type);
}
The continue statement is for continuing loops from the top of the loop; it does not stand on its own.

Categories