[英]how to make custom directive in angular for calculate the distance using google maps
我想對函數進行指令以使用Google地圖計算距離。 我為此項目使用angularjs和ionic,但是當我編寫此代碼時,出現錯誤。 這是代碼。
var control = angular.module('starter.controllers', []);
control.controller('MainCtrl', function($scope,$http, $ionicPopup, $timeout,$ionicModal) {
$scope.ori = "-7.048443, 110.441022";
$scope.dest = "-7.048264, 110.440388";
});
control.directive('distance', function () {
var calcRoute = function(ori,dest,cb) {
var dist;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer();
var request = {
origin:ori,
destination:dest,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
cb(null, response.routes[0].legs[0].distance.value / 1000);
}
else {
cb("error");
}
});
};
return{
restrict:"E",
scope: {
ori: "@",
dest:"@"
},
link: function(scope, elm, attrs) {
var ori = attrs.ori;
var dest = attrs.dest;
calcRoute(ori,dest, function (err, dist) {
if (!err) {
console.log(dist);
}else{
console.log(err);
}
});
}
};
});
在我的查看文件中:
<distance ori='"{{ori}}"' dest='"{{dest}}"'></distance>
並且控制台上的錯誤是:
Uncaught InvalidValueError: in property origin: not a string; and not a LatLng or LatLngLiteral: not an Object
我不明白錯誤的含義,請任何人幫助我,向我解釋代碼有什么問題。 謝謝 :)
也許這個
travelMode: google.maps.DirectionsTravelMode.DRIVING
應該是這個嗎?
google.maps.TravelMode.DRIVING
按照這個鏈接?
更新
嘗試這個
在此HTML代碼段中
<distance ori='"{{ori}}"' dest='"{{dest}}"'></distance>
您的ori ='“ {{ori}}”'(以及dest)都包含雙引號。 這導致指令內部的字符串如下所示:
"-7.048443, 110.441022"
這是一個字符串,但是它是一個在開頭和結尾都帶有字符“和”的字符串。 我認為您的ori和dest都不應使用雙引號,因為當它們到達Google API時它們仍然是字符串,但是在這種情況下,它們所帶有的字符很可能是Google API所不允許的。 Google Map API很可能想要這樣的字符串...
-7.048443, 110.441022 NOT THIS "-7.048443, 110.441022"
或者如果您在控制台中將它們打印出來,則將如下所示
"-7.048443, 110.441022" (good) ""-7.048443, 110.441022"" (bad)
在(不良)情況下,如果您這樣做
console.log(ori[0])
您將獲得(壞)字符串的第一個字符,即“它應該是-
由於API在第一個代碼上失敗,因此您將獲得源錯誤。 我認為,如果您改正ori ,則...
<distance ori="{{ori}}" dest='"{{dest}}"'></distance>
僅使用一組引號,則出於相同原因, dest將失敗。
最終,我認為將您的HTML代碼段更改為此將導致正確執行...
<distance ori="{{ori}}" dest="{{dest}}"></distance>
讓我們知道這是否有效...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.