I'm newer in javascript programming and i'm trying to understand async process. I've started a project and i would to know how to execute the code below as sync. I saw a lot of tutorials but, most of them are so superficial...
The code is simple, its a call to google maps api that pass an adress and return the latitude and longitude. After that, it should call server passing lat lng through url and return all locations near by the location specified.
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);
});
});