the helper should return google api call, prints undefined
once console , doesn't updatewhen getting response:
oncreated template:
this.distances = new reactivedict('restdistances');
helper:
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'); } }) });
let's try following - don't need 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); // reactive var automatically updated when set // 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 reactive var desired value template.distances.set('restdistances', response.routes[0].legs[0].distance.value); // there no need return here since // directionsservices.route callback , not outer function } else { console.log('route not found'); } }) });