I face some problems to get back the elevation value from a function. I'm not able to get that value. Would be great if somebody has a solution for that.
Here is my code:
function getElevation(latLng) {
seaLevel = 'Error';
var locations = [];
locations.push(latLng);
//Create a LocationElevationRequest object using the array[0] value
var positionalRequest = {
'locations': locations
}
//Initiate the location request
elevationService.getElevationForLocations(positionalRequest, function(results, status) {
if (status == google.maps.ElevationStatus.OK) {
// Retrieve the first result
if (results[0]) {
var seaLvl = parseFloat(results[0].elevation.toFixed(1));
}
dropElevation(seaLvl);
}
document.getElementById("response").innerHTML = seaLevel;
});
function dropElevation(tmpLevel) {
//alert(tmpLevel); at this point the value is correct
seaLevel = tmpLevel;
}
return seaLevel; //at this point the value is always as defined above
} //End function (getElevation)
The call of it looks like this:
var seaLvl = getElevation(latLng);
Thanks in advance to show me what I'm doing wrong
Guido
The elevations service is asynchronous. You must use the value inside the callback routine. Something like this:
elevationService.getElevationForLocations(positionalRequest, function(results, status)
{
if (status == google.maps.ElevationStatus.OK) {
// Retrieve the first result
if (results[0]) {
var seaLvl = parseFloat(results[0].elevation.toFixed(1));
dropElevation(seaLvl);
document.getElementById("response").innerHTML = seaLevel;
} else {
alert("no result");
}
}
});
And something like this:
var seaLvl = getElevation(latLng);
won't work (the value is not available until the message returns from the server).
Related
I'm trying to understand meteorjs and have a little question.
I wanted to create a getDateTime helper and wanted this helper to be available on the client and the server.
I then inserted this code in lib/helpers
function getDateTime() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth()+1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
if(month.toString().length == 1) {
var month = '0'+month;
}
if(day.toString().length == 1) {
var day = '0'+day;
}
if(hour.toString().length == 1) {
var hour = '0'+hour;
}
if(minute.toString().length == 1) {
var minute = '0'+minute;
}
if(second.toString().length == 1) {
var second = '0'+second;
}
var dateTime = year+'/'+month+'/'+day+' '+hour+':'+minute+':'+second;
return dateTime;
}
Unfortunately this function is not available ( "undefined" ) on the client.
When I look at the source, I can see it but it is encapsulated in:
(function(){ };
I don't quite understand why this is for.
What should I do to access the function?
Each .js file in a Meteor application is enclosed in an immediately-invoked function expression (function () { ... })() to prevent local variables from cluttering the global scope. To make that function accessible in other files, define it like this:
// note: no "var"
getDateTime = function () {
// ...
};
I have seen similar questions but I think my scenario is a bit different. Say I define a collection like this:
MyCol = new Meteor.Collection("myCol"
and I want to get a reference to 'MyCol' using the string 'myCol' - I have created the function below which seems to work:
function GetCollectionObject(name) {
for(var key in window) {
var value = window[key];
if (value instanceof Meteor.Collection) {
if (value._name == name) {
return value;
break;
}
}
}
return null;
}
Is this the only/best/most efficient way to do this?
Why don't you store your collections in a dictionary? It's way more efficient.
Dogs = new Meteor.Collection('dogs');
Cats = new Meteor.Collection('cats');
Alpacas = new Meteor.Collection('alpacas');
MyCollections = {
dogs: Dogs,
cats: Cats,
alpacas: Alpacas,
};
...
MyCollections['dogs'].doSomething();
I have a similar code:
Template.mytemplate.pippo = function() {
var returnValue;
asyncFunc(function (dataReturned) {
returnValue = dataReturned;
});
return returnValue;
}
I have try to load future on client side
var Future = Npm.require('fibers/future');
but don't work :(
How can I wait that asyncFunc return callBack finish to return template value returnValue
thanks!
There is a bit of a question of where you should be calling asyncFunc, but once you figure that out, your code should look something like this:
asyncFunc(function (dataReturned) {
Session.set('returnValue', dataReturned);
});
...
Session.setDefault('returnValue', "loading.."); // or some other default that is safe
Template.mytemplate.pippo = function() {
return Session.get('returnValue');
}
I confess that I do not get along very well with the Deferred object. I'm making a query to the database on several "Stores" and as a result I want to do a series of operations. This troubles me because the results are returned asynchronously and I have no way to perform the corresponding operation on the "store" you should. In short, the problem is that this piece of code always executes the same function on the same "Store"
for (var i = 0; i < schema['stores'].length; i++) {
storeName = schema['stores'][i].name;
var objeto = db.executeSql('SELECT MAX(date_upd) FROM ' + '"' + storeName + '"').done(
function(result, a){
//saveDataSynce(db, storeName, result);
console.log(result);
}
);
}
Whenever there is a loop on async operation, be very careful about function scope. In your example code, storeName inside the function will always be the last executed value. Use function scope as follow:
var getMax = function(storeName) {
db.executeSql('SELECT MAX(date_upd) FROM ' + '"' + storeName + '"').done(
function(result){
//saveDataSynce(db, storeName, result);
console.log(storeName, result);
}
);
}
for (var i = 0; i < schema['stores'].length; i++) {
getMax(schema['stores'][i].name);
}
However, preferred coding pattern for YDN-DB is NoSQL style as follow:
var getMax = function(storeName) {
var indexName = 'date_upd';
var key_range = null; // whole store
var limit = 1;
var offset = 0;
var reverse = true;
db.values(storeName, indexName, key_range, limit, offset, reverse).done(
function(results) {
var max_key = results[0]; // may be undefined. OK.
//saveDataSynce(db, storeName, max_key);
console.log(storeName, max_key);
}
);
}
Note that keys (primary or index) are always sorted by ascending order. Max key is the first key in reverse order.
Assume I have the following class:
class Example
{
function set something(value:String):void
{
trace("set something");
}
function doSomething():void
{
trace("something");
}
}
I can access the functions as objects like this:
var example:Example = new Example();
var asdf:Function = example.doSomething;
// this also works - example["doSomething"];
asdf(); // this trace: "something"
You do this all the time with events, for example. So, my big question is: Is there any way to get a handle on the setter? Is there some crazy function on Object or somewhere that I don't know about (please say yes :)
I want something like the following
var example:Example = new Example();
// the following won't work, because example.something is a string
var asdf:Function = example.something;
asdf("a value"); // this trace: "something"
The statement var asdf:Function = example.something; won't work because compiler treats example.something as a getter and returns string (or throws a write-only error if the getter is not implemented).
But since something is a property, you can do something like:
example["something"] = "a value"; //will trace 'set something'
//or
var property:String = "something";
example[property] = "some value"; //will trace 'set something'
You may try this:
class Example{
function set something(value:String):void{
trace("set something");
}
function doSomething():void{
trace("something");
}
}
class AnotherClass{
function callOtherClassFunction(funcObj:Obj):void{
if (funcObj.type == "method") {
funcObj.func.apply();
}
else if (funcObj.type == "setter") {
funcObj.obj[funcObj.func] = "something";
}
else if (funcObj.type == "getter") {
trace(funcObj.obj[funcObj.func]);
}
}
}
class Test{
function Test():void{
var e:Example = new Example();
var a:AnotherClass = new AnotherClass();
a.callOtherClassFunction({obj:e, type:"setter", func:"something"});
a.callOtherClassFunction({obj:e, type:"method", func:e.doSomething});
}
}