帮助者应该返回一个google api调用,但它会向控制台输出undefined
一次,并且在获得响应时不会更新:
onCreated模板:
this.distances = new ReactiveDict('restDistances');
助手:
distanceIs: function (destination, id){
var origin = Session.get('userLatLng');
Tracker.autorun(function(){
console.log(123);
console.log(Blaze._globalHelpers.getDistance(Template.instance().distances, id, origin, destination));
return Blaze._globalHelpers.getDistance(Template.instance().distances, id, origin, destination);
});
}
Template.registerHelper('getDistance', function(template, id, origin, destination){
var map;
var directionsDisplay;
var directionsService;
directionsDisplay = new google.maps.DirectionsRenderer;
directionsService = new google.maps.DirectionsService;
directionsDisplay.setMap(map);
directionsService.route({
origin: {lat: origin[0], lng: origin[1]},
destination: {lat: destination[1], lng: destination[0]},
travelMode: google.maps.TravelMode["DRIVING"]
}, function (response, status) {
if(status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
directionsDisplay.setOptions({suppressMarkers: true});
var distanceinmeter = (response.routes[0].legs[0].distance.value);
var timeInMinutes = response.routes[0].legs[0].duration.value;
console.log(distanceinmeter); //OK
template.set(id, distanceinmeter );
Tracker.autorun(function(){
console.log(template.get(id));
return template.get(id);
});
} else {
console.log('rout not found');
}
})
});
答案 0 :(得分:0)
让我们尝试以下方法 - 您甚至不需要Tracker.autorun()
。
Template.myTemplate.onCreated(function(){
this.distances = new ReactiveDict('restDistances');
});
Template.myTemplate.helpers({
distanceIs: function (destination, id){
const origin = Session.get('userLatLng');
Blaze._globalHelpers.getDistance(Template.instance(), id, origin, destination);
// the reactive var will automatically get updated when it is set from the
// callback of directionsService.route()
return Template.instance().distances.get('restDistances);
}
});
Template.registerHelper('getDistance', function(template, id, origin, destination){
var map, directionsDisplay, directionsService;
directionsDisplay = new google.maps.DirectionsRenderer;
directionsService = new google.maps.DirectionsService;
directionsDisplay.setMap(map);
directionsService.route({
origin: {lat: origin[0], lng: origin[1]},
destination: {lat: destination[1], lng: destination[0]},
travelMode: google.maps.TravelMode["DRIVING"]
}, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
directionsDisplay.setOptions({suppressMarkers: true});
// set the reactive var to the desired value
template.distances.set('restDistances', response.routes[0].legs[0].distance.value);
// there is no need to return here since it would be to the
// directionsServices.route callback and not the outer function
} else {
console.log('route not found');
}
})
});