Maximize accuracy in distance calculations by utilizing Google Maps for multiple destinations

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.

Answer №1

Is it necessary to execute the callback function for every business?

The DistanceMatrixService can fulfill your requirements, but it must be implemented correctly.

You have the option to include a maximum of 25 businesses in one request, and you will receive the distances from the user to all businesses in just one response.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can you transform attribute and value pairs from a DOM element into a JavaScript object?

Is there a quick method to transform a DOM element along with its attributes and values into a JavaScript object? For example, converting this snippet from the HTML page: <div id="snack" type="apple" color="red" size="large" quantity=3></div> ...

Is there a unique identifier associated with web explorers?

I'm conducting an experiment and I've noticed that Google is able to detect that it's the same computer, even when I change various settings. It seems to be identifying the explorer with a unique ID or something similar. I have tried everyth ...

Angular Graph - Modifying the Chart's Color Palette

Currently, I am utilizing the Angular Chart API to create graphs Angular Chart I have attempted to use the following options to define colors in the graph but it is not producing the expected results. Can you assist me in identifying what may be incorrec ...

Looking for jQuery bbq... is the grill fired up yet?

In my exploration of the jQuery bbq plugin, I noticed that there is no reference to document.hash in the code. I believe that the function for retrieving the hash is located at line 1094: function get_fragment( url ) { url = url || location.href; ...

Dynamic URL behavior in AngularJS

Let's say I have 3 links displayed on my webpage: A B C, When the user clicks on link A, it should trigger a function like this: var app = angular.module('myApp', []); app.controller('myCtrl', function($scope, $http) { $http.ge ...

Tips for using a JavaScript function to navigate to a specific division (<div>) on an HTML page

I am facing an issue where I need to redirect within the same HTML page that includes a add-form div. What I want is that when I click on a button, my redirection should be to a specific div containing some code. Currently, I have code that redirects to a ...

Issue with ngRepeat not functioning properly in ngMap

Although I have experience with similar tasks in the past, I've hit a roadblock while trying to accomplish something seemingly simple. This is my HTML code using ngMap: <html ng-app="myApp" ng-controller="mapCtrl as map"> .... <map center="5 ...

Using a React component to trigger an action when the Enter key

I have a react component that needs to respond to the "Enter" key press event. class MyComponent extends Component { componentDidMount() { console.log('componentDidMount'); document.removeEventListener('keypress', t ...

What could be causing this axios.get request to fail?

I am currently enrolled in Colt Steele's Web Developer bootcamp and facing a challenge... In the tutorial, we are using axios as 'request' has been discontinued, so I am trying to follow along with this change. My goal is to set up a Get r ...

Running JavaScript code within views

While dealing with AngularJS, I have an index page that includes a <div ui-view></div>. When a specific URL like #/offers/new is entered, it loads a page such as new-offer.html into the ui-view. In my javascript code block within the index.htm ...

AngularJS application is throwing an error indicating provider $q is not recognized

Could someone please advise on what might be the issue with my code snippet below: var app = angular.module('app', [ 'angular-cache', 'angular-loading-bar', 'ngAnimate', 'ngCookies', &a ...

Why does the custom method only trigger once with the addEventListener?

I am attempting to connect the "oninput" event of an input range element to a custom method defined in a corresponding typescript file. Here is the HTML element: <input type="range" id='motivation-grade' value="3" min="1" max="5"> This i ...

Achieving a transparent inner box-shadow effect on hover: a step-by-step guide

Is there a way to make the black ring transparent upon hover by changing box-shadow: 0 0 0 5px #000, 0 0 0 10px green to box-shadow: 0 0 0 5px transparent, 0 0 0 10px green? It doesn't seem to be working for me. Any suggestions on how to achieve this ...

Transform your JavaScript XMLHttpRequest into jQuery just like that

Is it possible to convert this code to jQuery? Perhaps by utilizing jQuery.get(). However, it seems that there is no responsetype of arraybuffer. var request = new XMLHttpRequest(); request.open("GET", url, true); request.responseType = "arraybuffer"; req ...

I am seeking a way to eliminate double quotation marks from a string without using the replace function

I need assistance in removing double quotes from the string "Hello". I have an array var ary = ['a', 'b' , 'c'] When I extract a value from the array, it returns the value in string format, such as ary[0] = "a", but I want i ...

Variety of properties determined by a "type" prop, expanding variations based on a value from the interface

I am trying to enhance a type based on a value from the main interface. If the type == multiline, it will have a specific interface, and if the type == icon, it will have a different type. import React, { memo, useCallback, ReactNode } from 'react&apo ...

Perhaps dividing numbers with regular expressions

My HTML textarea allows users to input numeric serial numbers in various formats - either inline, separated by any character, or in columns from an Excel file. The serial codes are either 14 characters long if the first character is "1," or always 15 char ...

Obtain the YouTube video identifier from a YouTube embedded link

Is there a way to extract just the YouTube ID from a given URL? https://www.youtube.com/embed/cqyziA30whE?controls=1&showinfo=0&rel=0&autoplay=0&loop=0 $(".youtube").click(function () { console.log(this.href.replace(new RegExp("em ...

Ensuring Vue.js correctly re-renders an array item

In my vue.js 2 project, I am working with an array that has the following structure: data() { return { ports: [ { id: 1, name: "example", "age": 10, scores: [ {index: 1, value: 100}, {index: 2, value: 200} ]}, { id: 2, ...

Example TypeScript code: Use the following function in Angular 5 to calculate the total by summing up the subtotals. This function multiplies the price by the quantity

I have a table shown in the image. I am looking to create a function that calculates price* quantity = subtotal for each row, and then sum up all the subtotals to get the total amount with Total=Sum(Subtotal). https://i.stack.imgur.com/4JjfL.png This is ...