Generate a url from a dropdown - json

Good morning,
I have the following issue.
I'm trying to setup a distance calculator from google maps.
Google is using its own api under that format:
https://maps.googleapis.com/maps/api/distancematrix/output?parameters
The output can be json or xml.
The idea is to use latitude and longitude to code the url:
https://maps.googleapis.com/maps/api/distancematrix/json?origins=25.479838,-80.422374&destinations=25.55727,-80.33372
That's an example of how the api provides the output.
Now, I want to be able to generate the url from a list of latitudes and longitudes I have.
Both fields would be a dropdown with autocomplete (the datalist function seems useful for that)
And once I click on a button like Calculate distance, it will generate the url from the 2 inputs I chose, and run it, In order to provide me the output.
The output would be in json so we should also find a way to have it interpreted in html.
I really would appreciate some help on that.
Thank you

Since Distance Matrix API endpoint:
https://maps.googleapis.com/maps/api/distancematrix/output?parameters
doesn't support JSONP you might want to utilize Distance Matrix Service as part of the Google Maps Javascript API.
Example
function calc() {
var originVals = $('#origins').val();
var destVals = $('#destinations').val();
var modeVal = $('#modes').val();
calculateDistances(originVals, destVals, modeVal,printInfo);
}
function printInfo(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
console.log('An error occured: ' + status);
return;
}
var output = JSON.stringify(response, null, 2);
$("#output").text(output);
}
function calculateDistances(originVals, destVals, mode, callback) {
var origins = [];
originVals.forEach(function (val) {
var ll = val.split(',');
origins.push(new google.maps.LatLng(ll[0], ll[1]));
});
var destinations = [];
destVals.forEach(function (val) {
var ll = val.split(',');
destinations.push(new google.maps.LatLng(ll[0], ll[1]));
});
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: origins,
destinations: destinations,
travelMode: mode.toUpperCase()
}, callback);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<body>
<table>
<tr>
<td colspan="2">
<label for="modes">Travel Modes</label>
<select id="modes">
<option value="driving">Driving</option>
<option value="walking">Walking</option>
<option value="bicycling">Bicycling</option>
<option value="transit">Transit</option>
</select>
</td>
</tr>
<tr>
<td>
<label for="origins">Origins</label>
</td>
<td>
<label for="destinations">Destinations</label>
</td>
</tr>
<tr>
<td>
<select id="origins" multiple="multiple">
<option value="49.256149, -123.074132">Vancouver+BC</option>
<option value="47.608136, -122.309813">Seattle</option>
</select>
</td>
<td>
<select id="destinations" multiple="multiple">
<option value="37.749624, -122.442407">San+Francisco</option>
<option value="48.430068, -123.365541">Victoria+BC</option>
</select>
</td>
</tr>
<tr>
<td colspan="2">
<input value="Calculate" type="button" onclick="calc();" />
</td>
</tr>
</table>
<br/>
<span>Result:</span>
<pre style="background-color: #c0c0c0" id="output"></pre>
</body>

Related

Google Sheets HTML Sidebar Select Multiple Options with Comma-separated Output

I have a Google Sheets job tracker with an HTML sidebar interface for adding new jobs. The sidebar has some dropdowns that pull options from a different sheet.
For the "Upcharge" dropdown, I'd like to be able to select multiple options by holding Control and then have those selections separated by commas on output.
This is my HTML file:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<b>Enter the details for your new job and click the <i><font color=#c5f27b>Save New Job</font></i> button.</b><br><br><br>
<table>
<tbody>
<tr>
<td><b>Upcharge:</b></td>
<td><select id="Upcharge">
<? for (let i in upchargeDPDWN) { ?>
<option value="<?=upchargeDPDWN[i]?>"><?=upchargeDPDWN[i]?></option>
<? } ?>
</select></td>
</tr>
<tr>
<td><b>Client:</b></td>
<td><select id="Client">
<? for (let i in clientDPDWN) { ?>
<option value="<?=clientDPDWN[i]?>"><?=clientDPDWN[i]?></option>
<? } ?>
</select></td>
</tr>
<tr>
<td><b>Description:</b> </td>
<td><input type="text" id="Description" size="22"><br></td>
</tr>
</tbody>
</table><br>
<!-- The user clicks this button to add the new job. -->
<center><input type="button" onclick='saveNew()' value="Save New Job"></center><br><br><br>
<script>
function saveNew(){
//Get the value of the input fields
var upcharge = document.getElementById("Upcharge").value
var client = document.getElementById("Client").value
var description = document.getElementById("Description").value
//Log input values in the web browser console
console.log(upcharge, client, description)
//Send values as arugments to the server side function
google.script.run.applyNew(upcharge, client, description)
}
</script>
</body>
</html>
This is my code to add the new job to the first empty row of the Job Log sheet:
function applyNew(upcharge, client, description) {
var ss = SpreadsheetApp.getActive()
var sheetLog = ss.getSheetByName("Job Log");
var sheetData = ss.getSheetByName("Data");
var rowCountData = sheetData.getMaxRows();
var columnToCheckData = sheetData.getRange("J:J").getValues();
var lastRowData = getLastRowSpecial(columnToCheckData);
if (lastRowData + 1 == rowCountData) {
sheetData.insertRowsAfter(lastRowData, 100);
}
// Get number of rows
var rowCount = sheetLog.getMaxRows();
//Select the column we will check for the first blank cell
var columnToCheck = sheetLog.getRange("B:B").getValues();
// Get the last row based on the data range of a single column.
var lastRow = getLastRowSpecial(columnToCheck);
// If the first empty row is the last row, insert a row before it
// (This is to ensure the data ranges for bar charts on the Dashboard sheet remain dynamic.)
if (lastRow + 1 == rowCount) {
sheetLog.insertRowAfter(lastRow);
}
var selectedRow = lastRow + 1;
//Apply upcharge to Column D = Column 4
sheetLog.getRange(selectedRow, 4).setValue(upcharge);
//Apply client to Column L = Column 12
sheetLog.getRange(selectedRow, 12).setValue(client);
//Apply description to Column N = Column 14
sheetLog.getRange(selectedRow, 14).setValue(description);
sheetLog.insertRowAfter(selectedRow);
};
Can someone please help me update this to allow for multiple options to be selected? All I can find via Google is scripts for selecting multiple items in data validation. Please let me know if any additional information is needed. Thanks in advance!
Here is a simple example of getting multiple options from a select element.
HTML_Test.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<select id="Upcharge" multiple size="4">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
<option value="option4">Option 4</option>
<option value="option5">Option 5</option>
<option value="option6">Option 6</option>
<option value="option7">Option 7</option>
<option value="option8">Option 8</option>
<option value="option9">Option 9</option>
<option value="option10">Option 10</option>
</select>
<br>
<input type="button" onclick='saveNew()' value="Save New Job">
<?!= include('JS_Test'); ?>
</body>
</html>
JS_Test.html
<script>
function saveNew() {
try {
let select = document.getElementById("Upcharge");
let options = select.options;
let selected = [];
for( let option of options ) {
if( option.selected ) selected.push(option.value);
}
alert(selected.toString());
}
catch(err) {
alert(err);
}
}
</script>
Screen shot
References
select multiple
select options

Sending the form data using json formate

I am using the JSON format to send the form data using but there is found error that "The POST method is not supported for this route. Supported methods: GET, HEAD". Actually I am using API of getting hotels.For this send the request through JSON format but I got error.
This is my API url in which I am sending the request- https://cdn.grnconnect.com/static-assets/documentation/GRN_v3-1.3/hotels/search_and_availability_request/#search-and-availability-request
<form class="mt40 mb50" action="#" method="post" id="myForm">
<input type="text" name="searchCity" id="searchCity">
<input type="text" name="searchCityCode" id="searchCityCode">
<input type="text" name="nationality" id="nationality">
<input type="text" name="checkin" id="checkin">
<input type="text" name="checkout" id="checkout">
<select class="form-control" name="adult" id="adult" style="height:40px;">
<option value="">Adult Member</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<button type="submit" class="awe-btn awe-btn-13 pr30 pl30 f16 bold font-hind"
id="find">Find
</button>
</form>
Script is-
$(document).ready(function(){
$("#find").click(function(){
var searchCity = $("#searchCity").val();
var adults = $("#adults").val();
var checkins = $("#checkin").val();
var checkouts = $("#checkout").val();
var nationality = $('#nationality').val();
// Checking for blank fields.
if (searchCity =='' || adults =='' || checkins =='' || checkouts =='' || nationality =='') {
alert("Please fill all fields...!!!!!!");
}
else {
$.ajax({
url:'https://cdn.grnconnect.com/api/v3/hotels',
type:'GET',
Data: {destination_code: search City, check-in: check-ins, check out: checkouts,client_nationality: nationality, cutoff_time: 5000, more_results: true,
hotel_info: false, rates: "comprehensive",rooms:adults},
success:function(data){
if(data['error'] == '0'){
window.location.href = 'https://cdn.grnconnect.com/api/v3/hotels';
}
},
error:function(e){
alert("error in request");
},
});
}
});
});
The route method is not specified in the route file for this route. Example:
Route::post('/hotels', 'HotelController#post')->name('hotel');
The URL is incorrect, the URL should be:
https://cdn.grnconnect.com/api/v3/hotels/availability
Instead of https://cdn.grnconnect.com/api/v3/hotels/

Store persistent HTML form data in Google Script

I wrote a Google Script web app to back up selected Gmail labels to a user-defined Google Drive location. Forml.html presents the data in a tabular format. On each row lives index (which is the checkbox), label and drive target.
We would like the data in each row to persist from one page load to the next so that a selected row stays selected. After I figure out how to make the data persist, then I can build a trigger which will make the app run on a schedule and back up the selected labels. Any thoughts on how best to achieve the effect of storing HTML form data over time? I'm thinking of using the properties service, but I don't know how I can change the initial doGet to choose between a blank form and a form with preexisting data.
Form.html
<div id="formDiv">
<form id="myForm" target="_self">
<table class="table table-hover">
<thead>
<tr>
<th scope="col">
<h3 span style="font-family:arial,helvetica,sans-serif;">Select</span></th>
<th scope="col">
<h3 span style="font-family:arial,helvetica,sans-serif;">Label</span></th>
<th scope="col">
<h3 span style="font-family:arial,helvetica,sans-serif;">Drive target</span></th>
</tr>
</thead>
<tbody>
<? var label = GmailApp.getUserLabels();
for (i = 0; i < label.length; i++) { ?>
<tr>
<td style="text-align: center;">
<span style="font-family:arial,helvetica,sans-serif;"><input id="index" type="checkbox" name="index" value="<?= [i]; ?>" /></span></td>
<td>
<span style="font-family:arial,helvetica,sans-serif;"><input id="label" type="text" style="border:none" size="60" name="label" value="<?= label[i].getName(); ?>" readonly /></span></td>
<td>
<span style="font-family:arial,helvetica,sans-serif;">Gmail Backup/<input id="target" type="text" size="60" maxlength="128" name="target" value="<?= label[i].getName(); ?>" /></span></td>
</tr>
<? } ?>
</tbody>
</table>
<p><input type="submit" value="Test" onclick="google.script.run.gmailBackup(this.parentNode.parentNode)" />
</p>
</form>
</div>
Code.gs
function doGet() {
var template = HtmlService.createTemplateFromFile("Form")
.evaluate()
.setSandboxMode(HtmlService.SandboxMode.NATIVE);
return template;
}
function gmailBackup(template) {
// Set HTML form variables
var indices = template.index;
var labels = template.label;
var targets = template.target;
for (i = 0; i < indices.length; i++) {
var index = indices[i].toString();
var label = labels[indices[i]].toString();
var target = "Gmail Backup/" + targets[indices[i]].toString();
...
}
I ended up using the PropertiesService to store HTML form properties on a per-user basis. This looks like it will work quite well (especially once I find out exactly where the data is stored per Where does Google Script PropertiesService store data?).
From Form.html
<input onclick="google.script.run.setProperties(this.parentNode.parentNode);" type="submit" value="Save" >
From Code.gs
function setProperties(form) {
var filledForm = PropertiesService.getUserProperties().setProperty("FORM", form);
}

knockout dynamically adding a row in a table

Problem Description:
I am using knockout and I have a table. In this table, I have 3 columns. The first column has a drop down list. I want to generate a new row whenever a user chooses a value from a drop down list.
Here's my fiddle :
http://jsfiddle.net/JPVUk/10/
<table class="table table-bordered">
<thead class="mbhead">
<tr class="mbrow">
<th>Type</th>
<th>Comment</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<select class="input-small">
<option value="">Type</option>
<option value="">One</option>
<option value="">Two</option>
<option value="">Three</option>
</select>
</td>
<td><input class="input-small"/></td>
<td><input class="input-small"/></td>
</tr>
</tbody>
</table>
<button id="saveButton">save</button>`
I want to accomplish this using knockout. Is there a way to accomplish it using knockout?
If I understand your question correctly, you want knockout to add a new row every time the selection in one of your dropdowns is changed.
You can do this by creating a view model with an observable array containing items. You then get your dropdown to insert items into it whenever the selection changes. See the following:
var ViewModel = function() {
var self = this;
self.items = ko.observableArray([{comment:'first comment', amount:0}]);
self.addNewItem = function(){
self.items.push(new Item('',0));
};
}
var Item = function(comment, amount) {
var self = this;
self.comment = ko.observable(comment);
self.amount = ko.observable(amount);
};
vm = new ViewModel()
ko.applyBindings(vm);
If you then add the following to your table markup:
<tbody data-bind="foreach: items">
<tr>
<td>
<select class="input-small" data-bind="event: { change: $root.addNewItem }">
<option value="">Type</option>
<option value="">One</option>
<option value="">Two</option>
<option value="">Three</option>
</select>
</td>
<td><input class="input-small" data-bind="value: comment"/></td>
<td><input class="input-small" data-bind="value: amount"/></td>
</tr>
</tbody>
I updated your JsFiddle here

HTML select or textarea

I'm trying to figure out how to create a test area where the user can either select from a list of items, or add to a textarea. Is this possible? Something like the following, except restrict the user to either selecting from the list, or entering into the textarea.
<tr>
<td width="100" class="formNames">Frequency</td>
<td colspan="2" class="cellColor">
<select name="yr" class="textbox">
<option value="0">-</option>
<option value="30">1</option>
<option value="30">2</option>
<option value="30">3</option>
<option value="30">4</option>
<option value="30">5</option>
</select>
</td>
<td width="10" class="formNames"> -or- </td>
<td class="formNames">
<input type="text" name="scheduletitle" class="textbox" value="default" />
</td>
</tr>
disable the other when data is changed in one. Using jQuery:
(function(){
var elements = $('select[name=yr],input[name=scheduletitle]');
elements.bind('change', function(){
var self = this;
elements.attr('disabled', false);
$(this).val() && elements.filter(function(){ return this != self; }).attr('disabled', true);
}
})();