无法从Javascript中的嵌套函数返回值
Unable to return value from nested function in Javascript
嘿,伙计们,我准备了一个带有html5地理定位的项目,它将计算距离。我在从Javascript中的嵌套函数返回值时遇到了问题,有人能帮我吗?
这是我的代码:
/* DISTANCE CALCULATOR FUNCTION */
function distanceCalc(latitudeB,longitudeB) {
var result;
if (navigator.geolocation) {
navigator.geolocation.watchPosition(showPosition);
}
function showPosition(position) {
calc(position.coords.latitude,position.coords.longitude);
}
function calc(latitudeA,longitudeA) {
var lat1 = latitudeA;
var lon1 = longitude;
var lat2 = latitudeB;
var lon2 = longitudeB;
var R = 6371; // km
var dLat = (lat2-lat1)*Math.PI/180;
var dLon = (lon2-lon1)*Math.PI/180;
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1*Math.PI/180) * Math.cos(lat2*Math.PI/180) *
Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.asin(Math.sqrt(a));
var d = R * c;
result = d.toFixed(1);
return result;
}
return result;
}
我想做一些类似的事情
var test = distanceCalc(44.35678,33.78546);
此代码不起作用,返回NAN值
脚本和逻辑中有很多错误。此外,当获取地理位置坐标时,会调用assync。试试看:
var DistanceCalc = function(latitudeB, longitudeB, onReadyCallback) {
this.latitudeB = latitudeB;
this.longitudeB = longitudeB;
this.callback = onReadyCallback;
//calling this.calc() here is ok...
};
DistanceCalc.prototype.calc = function()
{
var __calc = function(position) {
var lat1 = position.coords.latitude;
var lon1 = position.coords.longitude;
var lat2 = this.latitudeB;
var lon2 = this.longitudeB;
var R = 6371; // km
var dLat = (lat2-lat1)*Math.PI/180;
var dLon = (lon2-lon1)*Math.PI/180;
var a = (
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1*Math.PI/180) *
Math.cos(lat2*Math.PI/180) *
Math.sin(dLon/2) * Math.sin(dLon/2)
);
var c = 2 * Math.asin(Math.sqrt(a));
var d = R * c;
var result = d.toFixed(1);
this.callback(result);
}.bind(this); //bind to DistanceCalc object context
if (navigator.geolocation) {
navigator.geolocation.watchPosition(__calc);
} else {
console.log("geolocation is not available");
this.callback(null);
}
};
function doSomething(result) {
console.log(">>> ", result);
}
var calculator = new DistanceCalc(44.35678, 33.78546, doSomething);
calculator.calc();
相关文章:
- 用嵌套函数和默认函数定义函数
- d3中堆栈函数和嵌套函数之间的差异
- JavaScript 中的嵌套函数和 “this” 关键字
- Javascript中带有返回值的嵌套函数
- 访问嵌套函数结构中的JavaScript父函数变量
- 从嵌套函数访问函数属性
- 如何在javascript中使用嵌套函数作为生成器(使用“inner”yields)
- Javascript嵌套函数属性继承
- 我对“;返回true"嵌套函数内部;t工作
- JS中的嵌套函数
- 如何在嵌套函数中获取$(this)
- Jasmine中返回Deferred的模拟嵌套函数
- 如何在嵌套函数jquery上保持变量的值不变
- JavaScript中的深度嵌套函数
- Jquery从嵌套函数返回
- 使用'这'在类中的嵌套函数中
- 如何从上面的嵌套函数返回
- 从JavaScript中的嵌套函数返回值
- Javascript OOP-从函数返回一个值;s在对象内部's方法(嵌套函数)
- Javascript对象/名称空间-如何访问从嵌套函数添加的属性(包括示例)