I am faced with the task of determining the distance between a user and a company. Currently, I can calculate the distance between one user and one business. However, in the search view of my app, I need to calculate the distance between one user and multiple businesses.
For instance, when a user is logged in with a valid address and searches for a store to purchase shoes, the search results should display the distance between the user's location and all the listed businesses. This would look something like:
user <--> business 1 = 800m
user <--> business 2 = 1,650m
user <--> business 3 = 5.2km
user <--> business 4 = 1.2km
Although I can perform this calculation, the current method is not efficient as it takes too long to compute all the distances.
This is the code snippet being used:
function checkDistance() {
var splitUser = user.map.split(','),
userLat = parseFloat(splitUser[0]),
userLng = parseFloat(splitUser[1]),
splitBusi = busi.map.split(','),
busiLat = parseFloat(splitBusi[0]),
busiLng = parseFloat(splitBusi[1]);
var origin = new google.maps.LatLng(userLat,userLng),
destin = new google.maps.LatLng(busiLat,busiLng);
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [origin],
destinations: [destin],
travelMode: google.maps.TravelMode.DRIVING
}, callback);
function callback(response, status) {
if (status == google.maps.DistanceMatrixStatus.OK) {
var origins = response.originAddresses;
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
var distance = results[j].distance.text,
finalDistance = distance.split(' ')[0].replace(',', '.');
return finalDistance;
};
};
};
};
}
Is there a more optimized way to perform this calculation? Perhaps a different method altogether? Each time this function is executed for a business, it takes around 1-2 seconds to return the result. My project is based on AngularJS 1.x, so any suggestions or solutions can be JavaScript or Angular specific.