Passing Multiple Variables to HTML via Javascript - javascript

I am trying to pass a latitude AND a longitude from one page to another after it has been calculated by the google API.
For a compass website. Want to pass the lat and long both to another page to be used on that page. I am trying to pass them via the javascript.
The Java passing the variables.
var lat = marker.getPosition().lat();
var long = marker.getPosition().lng();
window.location.href = 'compass.html' + '#' + lat +'#' + long;
The Java recieving the variables
var latD = window.location.hash.substring(1);
var longD = window.location.hash.substring(2);
Instead of being split up they and being displayed together on the other page with the hash included. Like this:
-41.2864603?#174.77623600000004,
41.2864603?#174.77623600000004
I would like it to be like this:
-41.2864603
,174.77623600000004

Hash
The idea works, you just need to split the hash-string correctly.
//REM: On whatever.html
var lat = '-41.2864603';
var long = '174.77623600000004';
var tHref = 'compass.html' + '#' + lat +';' + long; //window.location.href = ..
//REM: On compass.html
var tHash = tHref.split('#').pop(); //window.location.hash.split('#').pop();
var tLat = tHash.split(';')[0];
var tLong = tHash.split(';')[1];
alert('Lat: ' + tLat + ', Long: ' + tLong);
QueryString
As another approach you could pass it as normal QueryString value like nbokmans recommended. Either separate or as stringified object. The difference is, that you need to implement your own js QueryString-Parser unless you get the values on the server. But you will find plenty of QueryString-Parsers on google.
Here is an example:
How can I get query string values in JavaScript?
localStorage
localStorage sounds like the easiest solution for me. You do not need to implement your own QueryString-Parser for it aswell. Just set it on whatever.html and read it on compass.html.
Check the example below:
https://developer.mozilla.org/de/docs/Web/API/Window/localStorage
//Set:
window.localStorage.setItem('whatever', JSON.stringify({lat: 1, long:2}));
//Get:
JSON.parse(window.localStorage.getItem('whatever'));

it should be like this :
var lat = marker.getPosition().lat();
var lng = marker.getPosition().lng();
window.location.href = 'compass.html?lat=' + '' + lat +'&longt=' + long;
To access these variables on that page,
const queryString = window.location.search;
console.log(queryString); // ?lat=19.234567&longt=73.23456
const urlParams = new URLSearchParams(queryString);
const lat = urlParams.get('lat')
const lng = urlParams.get('longt')
console.log(lat, lng);

Related

How to split JSON data from app script on a spreadsheet getting info from Wialon platform

I've collected some code to get this work, this GPS platform (Wialon) is for tracking vehicles and it has some functions to get notifications, one of them is to send them via server GET / POST method, so I have the following result in one cell:
{"|2020/08/13 18:57|CR-03 FR|0 km|🦂|JESUS SALVADOR GARCIA SCOTT|":""} //example
I separated some values by "||||" characters just to split them easily by SPLIT() formula in Google Sheets, but I want a cleaner result from the script, this is what I got from this code:
Please if you can help me to get this FINAL result, it didn't have to be necessarily formatted (date), this already splitted and separated by "|":
In this code are other functions that send the same data to a Telegram Group, ignore it, just put it here in case helps to anyone.
var token = "FILL IN YOUR OWN TOKEN"; // 1. FILL IN YOUR OWN TOKEN
var telegramUrl = "https://api.telegram.org/bot" + token;
var webAppUrl = "FILL IN YOUR GOOGLE WEB APP ADDRESS"; // 2. FILL IN YOUR GOOGLE WEB APP ADDRESS
var ssId = "FILL IN THE ID OF YOUR SPREADSHEET"; // 3. FILL IN THE ID OF YOUR SPREADSHEET
var adminID = "-XXXXXXXXX"; // 4. Fill in your own Telegram ID for debugging
function getMe() {
var url = telegramUrl + "/getMe";
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function setWebhook() {
var url = telegramUrl + "/setWebhook?url=" + webAppUrl;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function sendText(id,text) {
var url = telegramUrl + "/sendMessage?chat_id=" + id + "&text=" + encodeURIComponent(text);
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function doGet(e) {
return HtmlService.createHtmlOutput("Hi there");
}
function doPost(e) {
try {
// this is where telegram works
var data = JSON.parse(e.postData.contents);
var text = data.message.text;
var id = data.message.chat.id;
var name = data.message.chat.first_name + " " + data.message.chat.last_name;
var answer = "Hi " + name;
sendText(id,answer);
SpreadsheetApp.openById(ssId).getSheets()[0].appendRow([new Date(),id,name,text,answer]);
if(/^#/.test(text)) {
var sheetName = text.slice(1).split(" ")[0];
var sheet = SpreadsheetApp.openById(ssId).getSheetByName(sheetName) ? SpreadsheetApp.openById(ssId).getSheetByName(sheetName) : SpreadsheetApp.openById(ssId).insertSheet(sheetName);
var newText = text.split(" ").slice(1).join(" ");
sheet.appendRow([new Date(),id,name,newText,answer]);
sendText(id,"your text '" + newText + "' is now added to the sheet '" + sheetName + "'");
}
} catch(e) {
sendText(adminID, JSON.stringify(e,null,4));
}
}
This is the notification panel in the GPS platform and how it should be configured with the App Script:
I believe your goal as follows.
You want to split the following value in a cell of Google Spreadsheet.
{"|2020/08/13 18:57|CR-03 FR|0 km|🦂|JESUS SALVADOR GARCIA SCOTT|":""}
Sample formula:
=QUERY(ARRAYFORMULA(SPLIT(REGEXEXTRACT(SUBSTITUTE(A1:A5," km","|km"),"\|(\w.+)\|"),"|",TRUE,FALSE)),"select Col2,Col1,Col6,Col3,Col4")
The flow of this formula is as follows.
Put | to 0 km using SUBSTITUTE.
Retrieve |2020/08/13 18:57|CR-03 FR|0 km|🦂|JESUS SALVADOR GARCIA SCOTT| from {"|2020/08/13 18:57|CR-03 FR|0 km|🦂|JESUS SALVADOR GARCIA SCOTT|":""} using REGEXEXTRACT.
Split it with | using SPLIT.
Rearrange the columns using QUERY.
Result:
When your sample value is used with above formula, it becomes as follows.
Note:
Above proposed answer uses the built-in functions of Google Spreadsheet. If you want to convert above using Google Apps Script, please tell me. At that time, can you provide the sample values including {"|2020/08/13 18:57|CR-03 FR|0 km|🦂|JESUS SALVADOR GARCIA SCOTT|":""} from the response of the API? By this, I would like to think of the solution.
References:
SUBSTITUTE
REGEXEXTRACT
SPLIT
QUERY

Cannot select JSON elements

I'm brand new to web dev but I'm trying to create a Weather app using the openweatherapp API: https://openweathermap.org/current#geo . The JSON object is below:
{"coord":{"lon":5.38,"lat":34.72},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],"base":"stations","main":{"temp":280.903,"pressure":1000.23,"humidity":65,"temp_min":280.903,"temp_max":280.903,"sea_level":1031.37,"grnd_level":1000.23},"wind":{"speed":8.5,"deg":317},"clouds":{"all":0},"dt":1486603649,"sys":{"message":0.3449,"country":"DZ","sunrise":1486621797,"sunset":1486660553},"id":2475612,"name":"Tolga","cod":200}
Here's my javascript:
$(document).ready(function() {
// findind my latitude and longitude
if(navigator.geolocation){
function success(position){
var lat = position.coords.latitude.toString();
var long = position.coords.longitude.toString();
$("p").html("latitude: " + lat + "<br>longitude: " + long);
// using the API to get the weather from those lat and long values
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + long+"&appid=6a5aa3b59ebd571086cbd82be484ec8b", function(a){
temp = a[0].main.temp.toString();
hum = a[0].main.humidity.toString();
press= a[0].main.pressure.toString();
name = a[0].name;
$("h1").html(temp);
});
};
};
function failure(){
$("p").html("Not working");
};
navigator.geolocation.getCurrentPosition(success,failure);
});
The lat and long part is running fine but not the API for the weather.
Any help would be appreciated.
EDIT: Here's my codepen to make it simpler : https://codepen.io/tadm123/pen/OWojPx
Worked fine for me. Make sure that your browser has permission to know your location and that the computer has GPS. This probably will not work on a desktop.
Try manually setting the lat and long values and it should work.

JS parseFloat creates Int when parsing ASP.NET MVC model data

I want to parse Model data as a float to Javascript variable, but I will always get no decimals
function initMap() {
var latitude = parseFloat("#Model.latitude");
var longitude = parseFloat("#Model.longitude");
console.log(latitude + " " + longitude);
}
For example, if Model.latitude = 46.3245 I will get 46.
I have also tried this: var latitude = parseFloat("#Model.latitude").toFixed(4); but I get 46.0000
What can I do ?

Javascript to open file and read something using regular expressions

I would like to make a small gadget to use at work and show me the time of check in, from the morning.
I am trying to open a network file using http protocol and read from it the line which is referring to my check in.
This is located on our intranet and can be accessed like this:
filename = 'http://www.intranet.loc/docs/dru/Acces/' + ystr + '-' + mstr + '-' + dstr + '.mvm';
Every employer has a unique code for check in. The structure of the check In file is like this:
12:475663:1306285:072819:11:1:1:0:
12:512362:1306285:072837:11:1:1:0:
12:392058:1306285:072927:11:1:1:0:
12:516990:1306285:072947:11:1:1:0:
12:288789:1306285:073018:11:1:1:0:
12:510353:1306285:073032:11:1:1:0:
12:453338:1306285:073033:11:1:1:0:
12:510364:1306285:073153:11:1:1:0:
12:510640:1306285:073156:11:1:1:0:
In this example, 12 is the gate number, which I don't need, the second is my ID, the third is the current date, and what I need is the fourth (the hour).
Edit:
I am using this function to return the content of the mvm file with no luck:
function readfile(fileToRead) {
var allText = [];
var allTextLines = [];
var Lines = [];
var Cells = [];
var txtFile = new XMLHttpRequest();
txtFile.open("GET",fileToRead, true);
allText = txtFile.responseText;
allTextLines = allText.split(/r\r\n|\n/);
return allTextLines;
}
Do you really need a RegEx? Would it be possible to split the line by ":"?
$.get('http://www.intranet.loc/docs/dru/Acces/' + ystr + '-' + mstr + '-' + dstr + '.mvm', function(data) {
var lines = data.split("\n"),
values;
for (var i in lines) {
values = lines[i].split(':');
}
});
With this you would have everything you need.

access javascript variable into the .ashx page

I have a JavaScript, which returns 2 variables. I just want to access those variables in the generic handler(ashx) page but I can't. Can anybody give some suggestion?
var myArray = [txt, value];
var url = "insertComments.ashx?dat=" + myArray.join();
Change your Javascript :
var url = "insertComments.ashx?datTxt=" + txt + "&" + "datValue=" + value;
and in handler access that values with :
string txt = context.Request.Params["datTxt"];
string val = context.Request.Params["datValue"];

Categories

Resources