I am relatively new to JavaScript programming and I am currently trying to grasp the concepts of asynchronous processes. In my project, I am looking to execute the following code synchronously. Despite watching numerous tutorials on the subject, I find most of them to be too superficial for my understanding...
The code itself is quite simple - it involves making a call to the Google Maps API with an address as input and receiving back the latitude and longitude coordinates. Following this, the code should then make a call to the server with the lat/lng data in the URL to retrieve all locations near the specified location.
Client:
$scope.findLocations = function () {
var dist = 0.1;
// Execute this
getLatLong();
// Before this
$http.get('/api/locations/findByLocation/' + $scope.form.lng + '/' + $scope.form.lat + '/' + dist)
.success(function(data) {
$scope.locations = data;
$scope.form = {};
console.log("locations: ", data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
var getLatLong = function() {
var geo = new google.maps.Geocoder;
var address = $scope.form.adress;
console.log(address);
geo.geocode({'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log("Status geocoder OK");
$scope.form.lat = results[0].geometry.location.lat();
$scope.form.lng = results[0].geometry.location.lng();
var latlng = new google.maps.LatLng($scope.form.lat, $scope.form.lng);
var mapProp = {
center: latlng,
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};
var map = new google.maps.Map(document.getElementById("map"), mapProp);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: name
});
} else {
alert(status);
}
});
};
Server:
router.get('/api/locations/findByLocation/:lng/:lat/:dist', function(req, res){
var coords = [];
coords[0] = req.params.lng;
coords[1] = req.params.lat;
Location.find({
loc: {
$near: coords,
$maxDistance: req.params.dist
}
}).limit(30).exec(function(err, locations){
if(err){
res.json(err);
console.log(err);
}
res.json(locations);
});
});