Titanium Ti.GeoLocation.forwardGeocoder() is not converting Non US address to lat and long values - titanium

Ti.GeoLocation.forwardGeocoder() is not converting Non US address to lat and long values.
sample code below.
Ti.GeoLocation.forwardGeocoder('Hyderabad, India', function(e){
var lat = e.latitude;
var long = e.longitude;
});
with this code we are getting lat and long values are undefined.

The proper way to get US addresses, and everywhere else in the world (that Google can find) and display the Long/Lat on a titanium Map.
The code below uses the string variable: myAddress
var myAddress = address + ','+ city + ',' + postal + ',' + country //'Vieux Port, Montreal, Quebec, H2X3R4, Canada'
var xhrGeocode = Ti.Network.createHTTPClient();
xhrGeocode.setTimeout(120000);
xhrGeocode.onerror = function (e) {
alert('Google couldn\'t find the address... check your address');
};
xhrGeocode.onload = function (e) {
var response = JSON.parse(this.responseText);
if (response.status == 'OK' && response.results != undefined && response.results.length > 0) {
longitude = response.results[0].geometry.location.lng;
latitude = response.results[0].geometry.location.lat;
}
};
var urlMapRequest = "http://maps.google.com/maps/api/geocode/json?address=" + myAddress.replace(/ /g, '+');
urlMapRequest += "&sensor=" + (Ti.Geolocation.locationServicesEnabled == true);
xhrGeocode.open("GET", urlMapRequest);
xhrGeocode.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
xhrGeocode.send();

var addrReq = Titanium.Network.createHTTPClient();
var addrUrl = "http://maps.googleapis.com/maps/api/geocode/json?sensor=true&address="+ query;
addrReq.open("GET",addrUrl);
addrReq.send(null);
addrReq.onload = function()
{
var response = JSON.parse(this.responseText);
if(response.status == "OK"){
LT.Customlat=response.results[0].geometry.location.lat;
LT.Customlon=response.results[0].geometry.location.lng;
}

you will need to roll your own solution using google REST APIs, the underlying Titanium API does not support non-us addresses

Related

can I generate listenKey binance in app script

I try a lot of think to create listenKey in app script but nothing work.
the binance URL: https://binance-docs.github.io/apidocs/spot/en/#user-data-streams
this is my code:
function generated_key() {
var aPIKEY = '*****'; // key.
var secretKey = '****'; // Secret key.
var api = "/api/v3/userDataStream";
var timestamp = Number(new Date().getTime()).toFixed(0);
var string = "timestamp="+timestamp;
var baseUrl = "https://api1.binance.com";
var signature = Utilities.computeHmacSha256Signature(string, secretKey);
signature = signature.map(function(e) {
var v = (e < 0 ? e + 256 : e).toString(16);
return v.length == 1 ? "0" + v : v;
}).join("");
var query = "?" + string + "&signature=" + signature;
var params = {
'method': 'POST',
'headers': {'X-MBX-APIKEY': aPIKEY},
'muteHttpExceptions': true
};
var data = UrlFetchApp.fetch(baseUrl + api + query, params);
var obj = JSON.parse(data); // To JSON
Logger.log(obj)
}
I get the result error: {code=-1101.0, msg=Too many parameters; expected '0' and received '2'.}
any suggestion to do it.

Show a route on a map with Vue

I am working on a project with Vue and Leaflet that for now just shows a map and I want that when you give the start and end coordinates it colours the route from between those points (or many points and a route than goes through all of them). Unfortunately, I found that the plugin for Leaflet that uses OSRM for automating routing "will not work unless you configure a routing backend yourself". Is there an alternative to that? Any other open-source plugin for Vue Leaflet (or alternatively for OpenLayers(VueLayers) that can auto-track existing routes? Thank you in advance.
You could interface Openlayers directly with a service such as OpenRouteService https://openrouteservice.org/dev/#/api-docs/v2/directions/{profile}/json/post This code assumes a map routesMap with a vector layer orsRoute, and array routeComplete of coordinate pairs in view projection for start, optional waypoint, and end, and API key orsKey
var viewProj = routesMap.getView().getProjection();
var startA = ol.proj.transform(routeComplete[0], viewProj, 'EPSG:4326');
var viaA = routeComplete[1] ? ol.proj.transform(routeComplete[1], viewProj, 'EPSG:4326') : null;
var endA = ol.proj.transform(routeComplete[2], viewProj, 'EPSG:4326');
var startN = startA.toString();
var viaN = viaA ? viaA.toString() : null;
var endN = endA.toString();
var url = 'https://api.openrouteservice.org/v2/directions/driving-car/json';
var params = '{"coordinates":[[' + startN + '],[' + (viaN ? viaN + '],[' : '') + endN + ']]}';
var orsXhr = new XMLHttpRequest();
orsXhr.onreadystatechange = function() {
if (orsXhr.readyState == 4) {
if (orsXhr.status == 200) {
var route = JSON.parse(orsXhr.responseText).routes[0];
var linestring = route.geometry;
var distance = route.summary.distance;
var duration = route.summary.duration;
orsRoute.getSource().addFeature(
new ol.Feature({
geometry: new ol.format.Polyline().readGeometry(linestring).transform('EPSG:4326', viewProj),
name: 'Openrouteservice',
distance: distance,
duration: duration
})
);
orsRoute.getSource().setAttributions('© Powered by openrouteservice');
}
}
}
orsXhr.onerror = function(e) { console.log('error'); }
orsXhr.ontimeout = function(e) { console.log('timeout'); }
orsXhr.open('POST', url, true);
orsXhr.timeout = 3000;
orsXhr.setRequestHeader('Content-type', 'application/json');
orsXhr.setRequestHeader('Authorization', orsKey);
orsXhr.send(params);

Is it possible to select the word that is being read while using the SpeechSynthesisUtterance API?

Is it possible to select the word that is being read while using the SpeechSynthesisUtterance API?
Is there an event I can use to get the current spoken word and cursor position?
Here is what I have so far:
var msg = new SpeechSynthesisUtterance();
var voices = window.speechSynthesis.getVoices();
msg.voice = voices[10]; // Note: some voices don't support altering params
msg.voiceURI = 'native';
msg.volume = 1; // 0 to 1
msg.rate = 1; // 0.1 to 10
msg.pitch = 2; //0 to 2
msg.text = 'Hello World';
msg.lang = 'en-US';
msg.onend = function(e) {
console.log('Finished in ' + event.elapsedTime + ' seconds.');
};
speechSynthesis.speak(msg);
Example from here.
There was a related question that wrote out the words out to a span and I've extended that answer here to select the words as they are spoken.
var utterance = new SpeechSynthesisUtterance();
utterance.lang = 'en-UK';
utterance.rate = 1;
document.getElementById('playButton').onclick = function(){
var text = document.getElementById('textarea').value;
// create the utterance on play in case user called stop
// reference https://stackoverflow.com/a/47276578/441016
utterance = new SpeechSynthesisUtterance();
utterance.onboundary = onboundaryHandler;
utterance.text = text;
speechSynthesis.speak(utterance);
};
document.getElementById('pauseButton').onclick = function(){
if (speechSynthesis) {
speechSynthesis.pause();
}
};
document.getElementById('resumeButton').onclick = function(){
if (speechSynthesis) {
speechSynthesis.resume();
}
};
document.getElementById('stopButton').onclick = function(){
if (speechSynthesis) {
speechSynthesis.cancel();
}
};
function onboundaryHandler(event){
var textarea = document.getElementById('textarea');
var value = textarea.value;
var index = event.charIndex;
var word = getWordAt(value, index);
var anchorPosition = getWordStart(value, index);
var activePosition = anchorPosition + word.length;
textarea.focus();
if (textarea.setSelectionRange) {
textarea.setSelectionRange(anchorPosition, activePosition);
}
else {
var range = textarea.createTextRange();
range.collapse(true);
range.moveEnd('character', activePosition);
range.moveStart('character', anchorPosition);
range.select();
}
};
// Get the word of a string given the string and index
function getWordAt(str, pos) {
// Perform type conversions.
str = String(str);
pos = Number(pos) >>> 0;
// Search for the word's beginning and end.
var left = str.slice(0, pos + 1).search(/\S+$/),
right = str.slice(pos).search(/\s/);
// The last word in the string is a special case.
if (right < 0) {
return str.slice(left);
}
// Return the word, using the located bounds to extract it from the string.
return str.slice(left, right + pos);
}
// Get the position of the beginning of the word
function getWordStart(str, pos) {
str = String(str);
pos = Number(pos) >>> 0;
// Search for the word's beginning
var start = str.slice(0, pos + 1).search(/\S+$/);
return start;
}
<textarea id="textarea" style="width:100%;height:150px;">
Science Literacy is a way of approaching the world. It's a way of equipping yourself to interpret what happens in front of you. It's methods and tools that enable it to act as a kind of a utility belt necessary for what you encounter in the moment. It's methods of mathematical analysis, interpretation, some basic laws of physics so when someone says I have these two crystals and if you rub them together you get healthy. Rather than just discount it, because that's as lazy as accepting it, what you should do is inquire.
So do you know how to inquire? Every scientist would know how to start that conversation. Where did you get these? What does it cure? How does it work? How much does it cost? Can you demonstrate? Science literacy is vaccine against charlatans of the world that would exploit your ignorance of the forces of nature. Become scientifically literate.
</textarea><br>
<input type="button" id="playButton" value="Play"/>
<input type="button" id="pauseButton" value="Pause"/>
<input type="button" id="resumeButton" value="Resume"/>
<input type="button" id="stopButton" value="Stop"/>
MDN SpeechSynthesis
MDN SpeechSynthesisEvent
MDN Boundary
//NOTE: A USER MUST INTERACT WITH THE BROWSER before sound will play.
const msg = new SpeechSynthesisUtterance();
const voices = window.speechSynthesis.getVoices();
msg.voice = voices[10]; // Note: some voices don't support altering params
msg.voiceURI = 'native';
msg.volume = 1; // 0 to 1
msg.rate = 1; // 0.1 to 10
msg.pitch = 2; //0 to 2
txt = "I'm fine, borderline, so bad it hurts Think fast with your money cause it can't get much worse I get told that I'm far too old for number one perks".split(" ")
msg.text = txt;
msg.lang = 'en-US';
msg.onend = function(e) {
console.log('Finished in ' + event.elapsedTime + ' seconds.');
};
let gap = 240
let i = 0
speakTrack = setInterval(() => {
console.log(txt[i++])
//i++ < dont forget if you remove console log
if (i >= txt.length) {
i = 0
clearInterval(speakTrack)
}
}, gap)
speechSynthesis.speak(msg);
https://jsfiddle.net/Vinnywoo/bvt314sa

How to manage depending functions in nodejs

I am trying to teach myself nodejs and expressjs, however coming from java and c++ this is proving difficult to get used to.
I made a simple and messy module that it is supposed to return a weather forecast for a given zip code.
The way this happens is by taking the user zip code and using a google api to generate the geo coordinates for that zip code. I get the coordinates from the JASON file and then provide them to the next api call, this call is done to the forecast.io api and this time the weather data for the location is also taken from a JASON file.
Coming from java and with a not so solid background on JavaScript I am having a hard time making these two functions wait for one another, in this case I need the google api call to finish first because the coordinates it will provide are needed for the second api call. Can someone take a look at this code and tell me if the strategy I used is correct/ provide a suggestion so that I can know what is done in javascript in situations like this.
here is the code:
// The required modules.
var http = require("http");
var https = require("https");
//result object
var resultSet = {
latitude :"",
longitude:"",
localInfo:"",
weather:"",
humidity:"",
pressure:"",
time:""
};
//print out error messages
function printError(error){
console.error(error.message);
}
//Forecast API required information:
//key for the forecast IO app
var forecast_IO_Key = "this is my key, not publishing for security reasons";
var forecast_IO_Web_Adress = "https://api.forecast.io/forecast/";
//Create Forecast request string function
function createForecastRequest(latitude, longitude){
var request = forecast_IO_Web_Adress + forecast_IO_Key + "/"
+ latitude +"," + longitude;
return request;
}
//Google GEO API required information:
//Create Google Geo Request
var google_GEO_Web_Adress = "https://maps.googleapis.com/maps/api/geocode/json?address=";
function createGoogleGeoMapRequest(zipCode){
var request = google_GEO_Web_Adress+zipCode + "&sensor=false";
return request;
}
function get(zipCode){
// 1- Need to request google for geo locations using a given zip
var googleRequest = https.get(createGoogleGeoMapRequest(zipCode), function(response){
//console.log(createGoogleGeoMapRequest(zipCode));
var body = "";
var status = response.statusCode;
//a- Read the data.
response.on("data", function(chunk){
body+=chunk;
});
//b- Parse the data.
response.on("end", function(){
if(status === 200){
try{
var coordinates = JSON.parse(body);
resultSet.latitude = coordinates.results[0].geometry.location.lat;
resultSet.longitude = coordinates.results[0].geometry.location.lng;
resultSet.localInfo = coordinates.results[0].address_components[0].long_name + ", " +
coordinates.results[0].address_components[1].long_name + ", " +
coordinates.results[0].address_components[2].long_name + ", " +
coordinates.results[0].address_components[3].long_name + ". ";
}catch(error){
printError(error.message);
}finally{
connectToForecastIO(resultSet.latitude,resultSet.longitude);
}
}else{
printError({message: "Error with GEO API"+http.STATUS_CODES[response.statusCode]})
}
});
});
function connectToForecastIO(latitude,longitude){
var forecastRequest = https.get(createForecastRequest(latitude,longitude),function(response){
// console.log(createForecastRequest(latitude,longitude));
var body = "";
var status = response.statusCode;
//read the data
response.on("data", function(chunk){
body+=chunk;
});
//parse the data
response.on("end", function(){
try{
var weatherReport = JSON.parse(body);
resultSet.weather = weatherReport.currently.summary;
resultSet.humidity = weatherReport.currently.humidity;
resultSet.temperature = weatherReport.currently.temperature;
resultSet.pressure = weatherReport.currently.pressure;
resultSet.time = weatherReport.currently.time;
}catch(error){
printError(error.message);
}finally{
return resultSet;
}
});
});
}
}
//define the name of the outer module.
module.exports.get = get;
is the return statement properly placed? Is my use of finally proper in here? Please notice that I come from a java background and in java is perfectly fine to use the try{} catch(){} and finally{} blocks to execute closure code, it was the only way i managed this module to work. But now that i have incorporated some Express and I try to execute this module's method from another module, all I am getting is an undefined return.
You could use the Promise API, kind of like Futures in Java, so basically what you could do is wrap both functions in promises and the you could wait for resolve to execute the next function
var googleRequest = function(zipcode) {
return new Promise(function(resolve, reject) {
var request = https.get(createGoogleGeoMapRequest(zipCode), function(response) {
if (response.statusCode !== 200) {
reject(new Error('Failed to get request status:' + response.statusCode));
}
var body = "";
//a- Read the data.
response.on("data", function(chunk) {
body+=chunk;
});
//b- Parse the data.
response.on("end", function(body) {
var coordinates = JSON.parse(body);
resultSet.latitude = coordinates.results[0].geometry.location.lat;
resultSet.longitude = coordinates.results[0].geometry.location.lng;
resultSet.localInfo = coordinates.results[0].address_components[0].long_name + ", " +
coordinates.results[0].address_components[1].long_name + ", " +
coordinates.results[0].address_components[2].long_name + ", " +
coordinates.results[0].address_components[3].long_name + ". ";
resolve(resultSet);
})
});
request.on('error', function(err) {
reject(err);
});
});
}
After that you could just do
googleRequest(90210).then(function(result) {
connectToForecastIO(result.latitude, result.longitude);
}
You can find out more about Promise's usage in the Promise API docs
You should also note that there are several libraries available that allow for promise based http requests such as fetch

Get weather information in Titanium

Does someone know how to get weather information in Titanium? I read that the Google Weather API is no longer available. I have tried this link but I can't figure out how to put this to work.
Does someone have a working code? I would like to get the weather on my position given by longitude and latitude.
Titanium.Geolocation.getCurrentPosition(function(e) {
if (e.error) {
return;
} else {
var lon = e.coords.longitude;
var lat = e.coords.latitude;
if (Ti.Network.networkType == Ti.Network.NETWORK_NONE) {
return;
} else {
var client = Ti.Network.createHTTPClient({
onload : function(e) {
var weather = JSON.parse(this.responseText);
getweatherIcon(weather.weather[0].icon);
setweatherText(weather.weather[0].id, weather.main.temp);
},
onerror : function(e) {
},
timeout : 150000
});
client.open("GET", "http://api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude + "&appid=CreatedAppID");
client.send();
}
}
});
The "CreatedAppID" is the ID that I have created after creating an account on the provided link that is above.