Cordova+AngularJS中distanceInKmBetweenCoordinates未定义错误排查
解决Cordova+AngularJS 1中距离计算函数未定义的问题
首先,我一眼就揪出了最关键的问题:你定义的函数名和调用的函数名不匹配!
你写的函数是 distanceInKmBetweenEarthCoordinates,但在$http回调里调用的却是 distanceInKmBetweenCoordinates——少了"Earth"这个单词!这直接导致了ReferenceError,因为JS找不到你调用的那个函数名,这是最优先要修复的点。
接下来,我们再梳理其他容易踩坑的细节,确保整个流程顺畅:
1. 修正函数名并规范Angular作用域使用
与其用全局函数(容易污染全局空间),更符合AngularJS 1的做法是把计算函数挂载到$scope上,这样在controller的任何回调里都能稳定访问到:
formApp.controller('formProfile1', function($scope,$http,$location, $timeout){ // 把角度转弧度的函数挂载到$scope $scope.degreesToRadians = function(degrees) { return degrees * Math.PI / 180; }; // 统一函数名,和调用时保持一致 $scope.distanceInKmBetweenCoordinates = function(lat1, lon1, lat2, lon2) { var earthRadiusKm = 6371; var dLat = $scope.degreesToRadians(lat2-lat1); var dLon = $scope.degreesToRadians(lon2-lon1); lat1 = $scope.degreesToRadians(lat1); lat2 = $scope.degreesToRadians(lat2); var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); return earthRadiusKm * c; }; // 后续调用时直接用$scope前缀访问函数 // ... });
2. 修复地理定位的Angular digest cycle问题
navigator.geolocation.getCurrentPosition是原生Cordova API,它的回调不在Angular的digest循环里——这意味着你给$scope.userlatitude和$scope.userlongitude赋值后,Angular根本不知道这些变量更新了!后续使用这些变量时可能还是undefined,甚至间接影响函数调用。
解决方法是手动触发digest:
navigator.geolocation.getCurrentPosition(function(position) { // 用$apply包裹赋值操作,让Angular感知到变量变化 $scope.$apply(function() { $scope.userlongitude = position.coords.longitude; $scope.userlatitude = position.coords.latitude; }); });
3. 确保所有坐标都准备好再计算
地理定位和$http请求都是异步操作,它们的完成顺序不确定——可能$http请求先回来,但此时用户的位置还没获取到。所以在计算距离前,一定要先检查所有坐标变量都有值:
$http({ url: 'https://www.abcd.xyz/get_info.php', method: "GET", params: { tn_id: $scope.tn_id } }) .success(function(data) { if (data.success) { $scope.longitude = data.longitude; $scope.latitude = data.latitude; // 先验证所有坐标都存在,再执行计算 if ($scope.userlatitude && $scope.userlongitude && $scope.latitude && $scope.longitude) { $scope.distance = $scope.distanceInKmBetweenCoordinates($scope.userlatitude, $scope.userlongitude, $scope.latitude, $scope.longitude); } else { console.log("警告:缺少部分坐标数据,无法计算距离"); } } });
按这几步调整后,你应该就能解决函数未定义的错误,同时避免异步操作带来的变量未初始化问题。
内容的提问来源于stack exchange,提问作者Roxx
相关产品推荐
相关产品推荐

