Web app to launch google maps directions from link using lat & long - javascript

I have found the following link showing how to create links to launch navigation from a web app.
My JS code is:
// Build "ask for directions" url based on browser / OS type
function directionsButton(found) {
if (found) {
// Detect type of device to prepare URL for map directions
switch(true) {
case (/ipad|iphone|ipod/i.test(navigator.userAgent.toLowerCase())):
var directionsUrl = 'maps:?saddr=Current Location&daddr=' + $('#address1').val() + ' ' + $('#address2').val() + ' ' + $('#city').val() + ' ' + $('#state').val() + ' ' + $('#postcode').val() + ' ' + $('#country_id option:selected').text();
break;
case (/windows phone 7/i.test(navigator.userAgent.toLowerCase())):
var directionsUrl = 'maps:' + $('#address1').val() + $('#address2').val() + ' ' + $('#city').val() + ' ' + $('#state').val() + ' ' + $('#postcode').val() + ' ' + $('#country_id option:selected').text();
break;
case (/windows phone 8/i.test(navigator.userAgent.toLowerCase())):
var directionsUrl = 'bingmaps:?where=' + $('#address1').val() + ' ' + $('#address2').val() + ' ' + $('#city').val() + ' ' + $('#state').val() + ' ' + $('#postcode').val() + ' ' + $('#country_id option:selected').text();
break;
case (/android/i.test(navigator.userAgent.toLowerCase())):
var directionsUrl = 'geo:' + $('#address1').val() + ' ' + $('#address2').val() + ' ' + $('#city').val() + ' ' + $('#state').val() + ' ' + $('#postcode').val() + ' ' + $('#country_id option:selected').text();
break;
case (/blackberry/i.test(navigator.userAgent.toLowerCase())):
var directionsUrl = "javascript:blackberry.launch.newMap({'address':{'address1':'" + $('#address1').val() + ' ' + $('#address2').val() + "','city':'" + $('#city').val() + "','country':'" + $('#country_id option:selected').text() + "','stateProvince':'" + $('#state').val() + "','zipPostal':'" + $('#postcode').val() + "'}})";
break;
default:
var directionsUrl = 'http://maps.google.com?q=' + $('#address1').val() + ' ' + $('#address2').val() + ' ' + $('#city').val() + ' ' + $('#state').val() + ' ' + $('#postcode').val() + ' ' + $('#country_id option:selected').text();
}
$('#directions-button').attr('href', directionsUrl);
$('#directions-button').prop('disabled', false);
} else {
$('#directions-button').attr('href', '#');
$('#directions-button').prop('disabled', true);
}
}
I call the above function after the Google Map resolves the address like so (for successful map address geocoding):
directionsButton(true);
I would like to achieve the above for each browser / OS but using lat/long instead of address. I cannot to find the url structure examples for this.
thank you for any help.

First, most of your code only shows the location on the map, not the navigation to that location. I've changed this in the code below.
Now to your question.
The following isn't tested on all the devises, but is according to the respective documentation.
It assumes you have an input with id="lat" and one with id="lng":
// Build "ask for directions" url based on browser / OS type
function directionsButton(found) {
if (found) {
// Detect type of device to prepare URL for map directions
switch(true) {
case (/ipad|iphone|ipod/i.test(navigator.userAgent.toLowerCase())):
var directionsUrl = 'https://maps.google.com/?saddr=Current+Location&daddr=loc:' + $('#lat').val() + ',' + $('#lng').val();
break;
case (/windows phone 7/i.test(navigator.userAgent.toLowerCase())):
var directionsUrl = 'maps:' + $('#lat').val() + ',' + $('#lng').val();
break;
case (/windows phone 8/i.test(navigator.userAgent.toLowerCase())):
var directionsUrl = 'ms-drive-to:?destination.latitude=' + $('#lat').val() + '&destination.longitude=' + $('#lng').val();
break;
case (/android/i.test(navigator.userAgent.toLowerCase())):
var directionsUrl = 'google.navigation:q=' + $('#lat').val() + ',' + $('#lng').val();
break;
case (/blackberry/i.test(navigator.userAgent.toLowerCase())):
var directionsUrl = "javascript:blackberry.launch.newMap({'nav_end':{'latitude':" + $('#lat').val() + ",'longitude':" + $('#lng').val() + "}})";
break;
default:
var directionsUrl = 'https://maps.google.com?daddr=loc:' + $('#lat').val() + ',' + $('#lng').val();
}
$('#directions-button').attr('href', directionsUrl);
$('#directions-button').prop('disabled', false);
} else {
$('#directions-button').attr('href', '#');
$('#directions-button').prop('disabled', true);
}
}
Documentation used:
Blackberry:
https://developer.blackberry.com/native/documentation/device_platform/invocation/maps.html
iOS: https://developer.apple.com/library/content/featuredarticles/iPhoneURLScheme_Reference/MapLinks/MapLinks.html
Windows Phone 8: https : //msdn.microsoft.com/en-us/windows/uwp/launch-resume/launch-maps-app (I need a reputation of 10 to post more than 2 links)
For Windows Phone 7 I can't find the documentation anymore, it's old code. Android and desktop (default:) are tested.

Related

How to Add link to message

I was trying to make a notification with line notify but I dont know how to insert a command that puts a link from my google sheet to the message of the notification
// Line Notify
function onFormSubmit() {
var form = FormApp.openById('1ELczQ-uW1mauQrHFBpHK2pQnCCkvPf_4Nq-DPqM4nMw');
var fRes = form.getResponses();
var formResponse = fRes[fRes.length - 1];
var itemResponses = formResponse.getItemResponses();
var link = shape.getLink();
if (link != null && link.getLinkType() == SlidesApp.LinkType.URL) {
Logger.log('Shape has link to URL: ' + link.getUrl());
}
var msg = 'Electric Forklift Incentive'
+ ' \n' + itemResponses[5].getItem().getTitle() + ': ' + itemResponses[5].getResponse()
+ ' \n' + itemResponses[0].getItem().getTitle() + ': ' + itemResponses[0].getResponse()
+ ' \n' + itemResponses[1].getItem().getTitle() + ': ' + itemResponses[1].getResponse()
+ ' \n' + itemResponses[2].getItem().getTitle() + ': ' + itemResponses[2].getResponse()
+ ' \n' + itemResponses[3].getItem().getTitle() + ': ' + itemResponses[3].getResponse()
+ ' \n' + itemResponses[4].getItem().getTitle() + ': ' + itemResponses[4].getResponse()
+ ' \n' + itemResponses[4].getItem().getTitle() + ': ' + itemResponses[4].getResponse()
sendLineNotify(msg);
}
function sendLineNotify(message) {
var token = ["DdiU5tUykpSRpxRVqmEnM7ul3hcE3NEvc6Vzwknyzo7"];
var options = {
"method": "post",
"payload": "message=" + message,
"headers": {
"Authorization": "Bearer " + token
}
};
UrlFetchApp.fetch("https://notify-api.line.me/api/notify", options);
}
}

How to dynamically change size of the new window? [duplicate]

This question already has answers here:
How to get the image size (height & width) using JavaScript
(33 answers)
Closed 3 years ago.
I have a JS file connected with my JSP file. I want to show new window with a photo, every time I hit the link.
So far everything is okay, new window appears, but it has strictly specified width and height.
else if (nameClass == "label3"){
var myWindow = window.open("", "MsgWindow", "width=1600, height=1000");
myWindow.document.write("<img src='images/images/szafa.png'>");
}
How can I change that to have a dynamically changed size of the window, depends of the image size?
I have not tested this code but you will get the idea:
var myWindow = window.open("", "MsgWindow", "width=100, height=100, resizable=1, scrollbars=1, menubar=1");
myWindow.document.write(
'<script language="Javascript" type="text/javascript">' +
'function getElById(idVal)' +
'{' +
' if (document.getElementById != null)' +
' return document.getElementById(idVal)' +
' if (document.all != null)' +
' return document.all[idVal]' +
' alert("Problem getting element by id")' +
' return null' +
'}' +
'function resizer()' +
'{' +
' var elem = getElById("pic");' +
' if(elem)' +
' {' +
' var oH = elem.clip ? elem.clip.height : elem.offsetHeight;' +
' var oW = elem.clip ? elem.clip.width : elem.offsetWidth;' +
' window.resizeTo( oW, oH );' +
' var myW = 0, myH = 0, d = window.document.documentElement, b = window.document.body;' +
' if( window.innerWidth ) ' +
' { ' +
' myW = window.innerWidth; ' +
' myH = window.innerHeight; ' +
' }' +
' else if( d && d.clientWidth ) ' +
' { ' +
' myW = d.clientWidth; ' +
' myH = d.clientHeight; ' +
' }' +
' else if( b && b.clientWidth ) ' +
' { ' +
' myW = b.clientWidth; ' +
' myH = b.clientHeight; ' +
' }' +
' window.resizeTo(6+ oW + ( oW - myW ),6+ oH + ( oH - myH ) );' +
' }' +
'}' +
'</script>'
);
myWindow.document.write("<img id='pic' src='images/images/szafa.png'>");
myWindow.document.body.onLoad='resizer';
Or you can prepare a PHP script which will output the above HTML and provide the image name as URL query parameter to the script.

How can I filter null or undefined values from an ajax call?

I'm trying to create a simple class directory for my kid's class. I have a Array of students in JSON format and wrote an AJAX call for the kids' names, and parents information. But some don't have two parents or two sets of contact information? I have tried "if (studentData !== null) {
show the data} but that doesn't work.
function showStudents() {
var currentURL = window.location.origin;
$.ajax({ url: currentURL + '/api/students', method: 'GET'})
.then(function(studentData) {
console.log("------------------------------------");
console.log("URL: " + currentURL + "/api/students");
console.log("------------------------------------");
// Here we then log the NYTData to console, where it will show up as an object.
console.log(studentData);
console.log("------------------------------------");
for (var i = 0; i < studentData.length; i++ ) {
var studentSection = $('<div>');
studentSection.addClass('card');
studentSection.attr('id', 'studentCard-' + i);
studentSection.attr('style', 'width:25rem');
$('#studentSection').append(studentSection);
$('#studentCard-' + i ).append('<div class="card-header"><h3>' + studentData[i].firstName + ' ' + studentData[i].lastName + '</h3></div>');
$('#studentCard-' + i ).append('<ul class="list-group list-group-flush>');
$('#studentCard-' + i ).append('<li class="list-group-item"><h5>Parent(s):</h5>' + studentData[i].parent1 + ' & ' + studentData[i].parent2 +' </li>');
$('#studentCard-' + i ).append('<li class="list-group-item">' + 'phone: ' + studentData[i].contact1 + '<br> email: ' + studentData[i].email1 + '</li>');
$('#studentCard-' + i ).append('<li class="list-group-item">' + 'phone: ' + studentData[i].contact2 + '<br> email: ' + studentData[i].email2 + '</li>');
$('#studentCard-' + i ).append('</ul>');
$('#studentCard-' + i ).append('</div>');
}
});
}
It sounds like it's the parent1 or parent2 properties that might not exist, and the contact1 or contact2 properties that might not exist. It doesn't make sense to test if the entire response is null - just check those properties instead. For example:
for (var i = 0; i < studentData.length; i++ ) {
var studentSection = $('<div>');
studentSection.addClass('card');
studentSection.attr('id', 'studentCard-' + i);
studentSection.attr('style', 'width:25rem');
$('#studentSection').append(studentSection);
$('#studentCard-' + i ).append('<div class="card-header"><h3>' + studentData[i].firstName + ' ' + studentData[i].lastName + '</h3></div>');
$('#studentCard-' + i ).append('<ul class="list-group list-group-flush>');
// Start of changes
const parentStr = [studentData[i].parent1, studentData[i].parent2].filter(Boolean).join(' & ');
$('#studentCard-' + i ).append('<li class="list-group-item"><h5>Parent(s):</h5>' + parentStr +' </li>');
if (studentData[i].contact1) {
$('#studentCard-' + i ).append('<li class="list-group-item">' + 'phone: ' + studentData[i].contact1 + '<br> email: ' + studentData[i].email1 + '</li>');
}
if (studentData[i].contact2) {
$('#studentCard-' + i ).append('<li class="list-group-item">' + 'phone: ' + studentData[i].contact2 + '<br> email: ' + studentData[i].email2 + '</li>');
}
// End of changes
$('#studentCard-' + i ).append('</ul>');
$('#studentCard-' + i ).append('</div>');
}
Your script structure could be improved too - unless each card's id is particularly important, it would make more sense to use a class instead of unique ids for every single element, or perhaps to leave it off entirely if you're only using it to select the newly created container. You already have a reference to the element you just created with studentSection, so just reference that variable again. You can also use method chaining to reduce your syntax noise:
CSS:
.card {
width: 25rem;
}
(that will keep you from having to manually set the width of each created element in your JS)
JS loop:
for (var i = 0; i < studentData.length; i++ ) {
var studentSection = $('<div>');
$('#studentSection').append(studentSection);
const parentStr = [studentData[i].parent1, studentData[i].parent2].filter(Boolean).join(' & ');
studentSection.addClass('card')
.append('<div class="card-header"><h3>' + studentData[i].firstName + ' ' + studentData[i].lastName + '</h3></div>')
.append('<ul class="list-group list-group-flush>')
.append('<li class="list-group-item"><h5>Parent(s):</h5>' + parentStr +' </li>');
if (studentData[i].contact1) {
studentSection.append('<li class="list-group-item">' + 'phone: ' + studentData[i].contact1 + '<br> email: ' + studentData[i].email1 + '</li>');
}
if (studentData[i].contact2) {
studentSection.append('<li class="list-group-item">' + 'phone: ' + studentData[i].contact2 + '<br> email: ' + studentData[i].email2 + '</li>');
}
studentSection.append('</ul>');
.append('</div>');
}
(Or, even better, use template literals instead)

Adding field in view ASP.NET MVC

I working on one application, and I started learning ASP.NET so I am begginer and I am trying to add one field in view.
So, I have Firstname,Address, ZIP, State etc and I want for every medical provider add his|her speciality. I create a table and make connection beatween two table.
When I add SPeciality, it doesnt show up in view. I have no idea where I made mistake.
https://i.imgur.com/YBc5dVZ.jpg
https://i.imgur.com/m0haaIW.jpg
https://i.imgur.com/mAvjNLc.jpg
var id = $(this).attr('data-id');
$.getJSON("/NfDocuments/MedicalInput", { id: id },
function (data) {
$('#medInput').empty();
$.each(data, function () {
// $("#medInput").append("'" + this.Id + "'");
//console.log(this.Id);
var medInput = document.getElementById("medInput");
medInput.value = this.Firstname + ' - ' + this.Zip + ' ' + this.Address1 + ',' + this.City + ', ' + this.State + ' - ' + this.Mobile;
});
});
Any suggestion, comment ?
medInput.value = this.Firstname + ' - '
+ this.Zip + ' '
+ this.Address1 + ','
+ this.City + ', '
+ this.State + ' - '
+ this.Mobile;
You need to append this.SpecialityName (or whatever you have it named as when returned to the view) to medInput.Value:
medInput.value = this.Firstname + ' - '
+ this.Zip + ' '
+ this.Address1 + ','
+ this.City + ', '
+ this.State + ' - '
+ this.Mobile + ' - '
+ this.SpecialityName;
I'm assuming the id of each speciality is this.TypeId and that you have already mapped TypeId to some kind of SpecialityName before sending the object back to the view.

Yahoo finance xchange - taking the last update time

I'm doing a query on Yahoo finance xchange, but seems the time of update is not the most updated. Seems random, for each refresh, this value change, sometimes most updated, and sometimes less updated.
There is a way to always get the last time it was updated ?
Thank you.
$.getJSON("https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22USDUSD%22%2C%22USDEUR%22%2C%20%22USDJPY%22%2C%20%22USDCNY%22%2C%20%22USDGBP%22%2C%20%22USDBRL%22%2C%20%22EUREUR%22%20%2C%22EURUSD%22%2C%20%22EURJPY%22%2C%20%22EURCNY%22%2C%20%22EURGBP%22%2C%20%22EURBRL%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=", function (data) {
var indices = '<p style=\"border:1px solid #ccc; width:auto; padding:0 10px; background:#ddd;\"><strong>' + data.query.results.rate[0].Name + '</strong> ' + money(data.query.results.rate[0].Rate) + '</p>' +
'<p><strong>' + data.query.results.rate[1].Name + '</strong> (Fechamento ' + money(data.query.results.rate[1].Rate) + ') - ' + data.query.results.rate[1].Date + ' - ' + data.query.results.rate[1].Time + '</p>' +
'<p><strong>' + data.query.results.rate[2].Name + '</strong> (Fechamento ' + money(data.query.results.rate[2].Rate) + ') - ' + data.query.results.rate[2].Date + ' - ' + data.query.results.rate[2].Time + '</p>' +
'<p><strong>' + data.query.results.rate[3].Name + '</strong> (Fechamento ' + money(data.query.results.rate[3].Rate) + ') - ' + data.query.results.rate[3].Date + ' - ' + data.query.results.rate[3].Time + '</p>' +
'<p><strong>' + data.query.results.rate[4].Name + '</strong> (Fechamento ' + money(data.query.results.rate[4].Rate) + ') - ' + data.query.results.rate[4].Date + ' - ' + data.query.results.rate[4].Time + '</p>' +
'<p><strong>' + data.query.results.rate[5].Name + '</strong> (Fechamento ' + money(data.query.results.rate[5].Rate) + ') - ' + data.query.results.rate[5].Date + ' - ' + data.query.results.rate[5].Time + '</p>' +
'<p style=\"border:1px solid #ccc; width:auto; margin:20px 0 0; padding:0 10px; background:#ddd;\"><strong>' + data.query.results.rate[6].Name + '</strong> ' + money(data.query.results.rate[6].Rate) + '</p>' +
'<p><strong>' + data.query.results.rate[8].Name + '</strong> (Fechamento ' + money(data.query.results.rate[8].Rate) + ') - ' + data.query.results.rate[8].Date + ' - ' + data.query.results.rate[8].Time + '</p>' +
'<p><strong>' + data.query.results.rate[7].Name + '</strong> (Fechamento ' + money(data.query.results.rate[7].Rate) + ') - ' + data.query.results.rate[7].Date + ' - ' + data.query.results.rate[7].Time + '</p>' +
'<p><strong>' + data.query.results.rate[9].Name + '</strong> (Fechamento ' + money(data.query.results.rate[9].Rate) + ') - ' + data.query.results.rate[9].Date + ' - ' + data.query.results.rate[9].Time + '</p>' +
'<p><strong>' + data.query.results.rate[10].Name + '</strong> (Fechamento ' + money(data.query.results.rate[10].Rate) + ') - ' + data.query.results.rate[10].Date + ' - ' + data.query.results.rate[10].Time + '</p>' +
'<p><strong>' + data.query.results.rate[11].Name + '</strong> (Fechamento ' + money(data.query.results.rate[11].Rate) + ') - ' + data.query.results.rate[11].Date + ' - ' + data.query.results.rate[11].Time + '</p>';
$('#info').html(indices);
});
money = function (n) {
var
c = 4,
d = ',',
t = '.',
s = n < 0 ? "-" : "",
i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
j = (j = i.length) > 3 ? j % 3 : 0;
return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};
Well, I ended up constructing a date for each element in the array (map) and then filtering them to the oldest date (reduce)
what do you want to do with this date, I am not sure but here it is...
UPDATED
updated to return full JSON record containing the latest date/time stamp (instead of returning only the latest date)
// sample response
var response = {"query":{"count":12,"created":"2016-04-29T20:13:39Z","lang":"en-us","results":{"rate":[{"id":"USDUSD","Name":"USD/USD","Rate":"1.0000","Date":"N/A","Time":"N/A","Ask":"1.0000","Bid":"1.0000"},
{"id":"USDEUR","Name":"USD/EUR","Rate":"0.8775","Date":"4/29/2016", "Time":"12:38pm","Ask":"0.8777","Bid":"0.8775"},{"id":"USDJPY","Name":"USD/JPY","Rate":"107.3910","Date":"4/29/2016","Time": "2:55pm","Ask":"107.3940","Bid":"107.3910"},{"id":"USDCNY","Name":"USD/CNY","Rate":"6.4868","Date":"4/29/2016","Time":"12:49pm","Ask":"6.4878","Bid":"6.4868"},{"id":"USDGBP","Name":"USD/GBP","Rate":"0.6843","Date":"4/29/2016","Time":"1:15pm","Ask":"0.6844","Bid":"0.6843"},{"id":"USDBRL","Name":"USD/BRL","Rate":"3.4492","Date":"4/29/2016","Time":"3:33pm","Ask":"3.4496","Bid":"3.4492"},{"id":"EUREUR","Name":"EUR/EUR","Rate":"1.0000","Date":"1/29/2016","Time":"8:26am","Ask":"1.0002","Bid":"0.9998"},{"id":"EURUSD","Name":"EUR/USD","Rate":"1.1443","Date":"4/29/2016","Time":"3:08pm","Ask":"1.1443","Bid":"1.1443"},{"id":"EURJPY","Name":"EUR/JPY","Rate":"122.5650","Date":"4/29/2016","Time":"4:00pm","Ask":"122.6200","Bid":"122.5100"},{"id":"EURCNY","Name":"EUR/CNY","Rate":"7.4054","Date":"4/29/2016","Time":"2:08pm","Ask":"7.4070","Bid":"7.4037"},{"id":"EURGBP","Name":"EUR/GBP","Rate":"0.7836","Date":"4/29/2016","Time":"3:22pm","Ask":"0.7837","Bid":"0.7836"},{"id":"EURBRL","Name":"EUR/BRL","Rate":"3.9637","Date":"4/29/2016","Time":"4:28pm","Ask":"3.9679","Bid":"3.9595"}]}}};
//console.log(response.query.results.rate);
var times = response.query.results.rate.map(function(elem){
if( elem.Time === 'N/A' || elem.Time === 0){
elem.fullDateTimeStamp = elem.Time;
//console.log(elem);
return elem;
}
// create full date from the time (using time and date combined)
// 1) is it AM or PM
var elemIsPm = (elem.Time.substring(elem.Time.length-2).indexOf("am") == -1);
// 2) remove AM/PM and get hour:min into array
var elemArr = elem.Time.substring(0, elem.Time.length-2).split(":");
// 3) add 12 hours if PM and not noon
if( elemIsPm && elemArr[0] != 12){
elemArr[0] = parseInt(elemArr[0]) + 12;
}
//console.log(elemArr[0]);
// 4) however, if it is 12, we deduct 12 if it's not PM
if( elemArr[0] == 12 && !elemIsPm ){
elemArr[0] = elemArr[0] - 12;
}
// 5) create date object
var elemDateString = elem.Date;
var elemDateOnly = new Date(elemDateString);
//console.log(elemDateOnly);
var elemTS = new Date(elemDateOnly.getFullYear(), elemDateOnly.getMonth(), elemDateOnly.getDate(), elemArr[0], elemArr[1], 0, 0);
elem.fullDateTimeStamp = elemTS;
// console.log(elem);
// 4) return
return elem;
});
console.log( times );
var lastOne = times.reduce(function(prevVal, elem) {
// console.log('p');
// console.log(prevVal );
// console.log('e');
// console.log(elem );
if( prevVal === 'N/A' || prevVal === 0 || prevVal.Time){
return elem;
}
//console.log(prevVal.fullDateTimeStamp);
return (prevVal.fullDateTimeStamp < elem.fullDateTimeStamp)? elem : prevVal;
}, 0);
document.getElementById('latest').innerHTML = JSON.stringify(lastOne);
console.log('====> ');
console.log( JSON.stringify(lastOne.fullDateTimeStamp) );
Last date:
<div id='latest'></div>

Categories

Resources