Google Maps API - Adjustment of closest marker function to display the closest n markers

I recently came across a helpful formula in this question that allows me to determine the nearest marker on the map based on the current position. However, I am now looking to enhance this formula so that it can identify not just the closest marker, but the closest n number of locations (such as the top 5 or top 10 closest). I'm unsure about how to go about implementing this modification.

Below is the adjusted formula I am currently using:

function rad(x) {return x*Math.PI/180;}
function find_closest_marker(center, map) {
    var lat = center.lat();
    var lng = center.lng();
    var R = 6371; // radius of earth in km
    var distances = [];
    var closest = -1;
    for( i=0;i<markers.length; i++ ) {
        var mlat = markers[i].position.lat();
        var mlng = markers[i].position.lng();
        var dLat  = rad(mlat - lat);
        var dLong = rad(mlng - lng);
        var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(rad(lat)) * Math.cos(rad(lat)) * Math.sin(dLong/2) * Math.sin(dLong/2);
        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
        var d = R * c;
        distances[i] = d;
        if ( closest == -1 || d < distances[closest] ) {
            closest = i;
        }
    }

    //Displaying the title of the closest marker
    console.log(markers[closest].title);
}

This is how I load the markers initially:

// Adding markers to the map
function setMarkers(center, map) {
    var json = (function () { 
        var json = null; 
        $.ajax({ 
            'async': false, 
            'global': false, 
            'url': "js/data.json", 
            'dataType': "json", 
            'success': function (data) {
                 json = data; 
             }
        });
        return json;
    })();
    // Loop over each JSON element
    for (var i = 0, length = json.length; i < length; i++) {
        var data = json[i],
        latLng = new google.maps.LatLng(data.lat, data.lon);
        
        // Creating and placing a marker on the map
        var icon = 'assets/marker.png';
        var marker = new google.maps.Marker({
            position: latLng,
            map: map,
            icon: icon,
            title: data.loc
        });
        markers.push(marker);
        infoBox(map, marker, data);
    }
}

Any insights on how I could further modify the formula to identify the closest n markers instead of just the single closest one?

Answer №1

To solve this problem, you can make use of the slightly modified findClosestN function referenced in this specific question. In this adaptation, the code changes gmarkers to markers, and adjusts the function so that it returns an array labeled closest limited to a specified number of results.

function findClosestN(pt, numberOfResults) {
    var closest = [];
    for (var i = 0; i < markers.length; i++) {
        markers[i].distance = google.maps.geometry.spherical.computeDistanceBetween(pt, markers[i].getPosition());
        markers[i].setMap(null);
        closest.push(markers[i]);
    }
    closest.sort(sortByDist);
    return closest.splice(0,numberOfResults);
}

function sortByDist(a, b) {
    return (a.distance - b.distance)
}

For a demonstration of how this works, you can refer to the proof of concept fiddle.

Here is the code snippet:

var geocoder = null;
var map = null;
var customerMarker = null;
var markers = [];
var closest = [];

// Remaining JavaScript code...
// CSS Code...
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&key=YOUR_API_KEY"></script>
 // HTML Code...

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

Manipulating webpage content with JavaScript

How can I provide visual feedback to a user while an ajax request is in progress? For example, when a user clicks a 'process' button that triggers an AJAX request to a server-side script, they should see a 'loading...' message and a gra ...

Implementing hover-over tooltips with JavaScript and HTML

New JS function: function DisplayToolTip() { let x = event.clientX; let y = event.clientY; document.getElementById('divToolTip').style.left = x + 'px'; document.getElementById('divToolTip').style.top = y + &ap ...

Getting the values of several labels using a class name - a comprehensive guide

Is there a way to retrieve the values of labels with the "timeAuction" class? I'm currently working on a JavaScript function that will target each label with the class name timeAuction and adjust its value. The number of labels with this class can va ...

Each Jest test file should have a specified window.location

After upgrading to Jest 22, I encountered an issue with mocking window.location. Previously, this method worked fine but stopped working after the update. Object.defineProperty(window.location, 'href', { writable: true, value: 'http ...

Fetching data using ajax and then appending it to the webpage

I am currently loading content from a PHP file in JSON format. products.php <?php $stmt = $mysqli->prepare("SELECT * FROM products LIMIT 10"); $stmt->execute(); $products = $stmt->get_result(); $produc ...

A file can be generated with PHP, however, it takes thirty minutes for it to be viewable on the browser

Currently, I am working on a browser-based game where the process of creating an account involves using a JS file to call a PHP file (POST) to write an XML file. The issue at hand is that after successfully writing the XML file with the correct content in ...

What does it mean in Javascript when b1 is undefined while o1 has a value and is equal to b1?

Having some issues getting variables to work with drop down options on a page. At first, I couldn't even extract a value from the function but managed to do so by removing "var" from o1. Strange thing is, when I type o1 into the js console on chrome i ...

Is there a problem with the Time Graph in Flot?

I am currently working on graphing a month using Flot, with data for each day or possibly every other day. I need to set up ticks. To retrieve my time values, I am utilizing the following method: $date = strtotime($rowData[0]); // 2013-01-01 $myData = j ...

Server for Electron application using Node.js

Working on a project that involves Electron + React, I need to develop a feature that allows users to save files on the server similar to Google Drive. Currently, I am setting up the server side using express but I'm not sure how to send files to the ...

when within a 'for in' loop

Querying Object Equivalence: I find myself struggling to comprehend the flow of my code and how I can rectify it. Within the areEqual function, I am comparing the "value" property of two objects. If they match -> isEqual=true -> continue with the ...

The jQuery bindings are only functional after using the alert function following the .load and .getScript methods

Calling out all jQuery Ajax experts! I've been tinkering with jQuery 1.7.2 and even tried 1.5.1... <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> The main page loads an ext ...

What is the best way to instantly update $scope when working with non-angular code?

Working with a non-angular library requires establishing communication between them. <div id="MoipWidget" data-token="{{personaltoken}}" callback-method-success="successCB" callback-method-error="errorCB"></div> Upon page load, a token must b ...

Execute the cucumber cli programmatically in the index.js file of a node application

Recently, I received an automation framework built in CucumberJS and Node with Selenium. However, the framework is using an outdated version of Cucumber that relies on promises. Wanting to take advantage of the latest synchronous step feature, I decided to ...

javascriptif the number is a whole number and evenly divisible

I am currently developing a script that tracks the distance traveled by some dogs in meters. It is basically just a gif running in a loop. What I want to achieve now is to display an image every 50 meters for a duration of 3 seconds. Here's my attempt ...

The clash between Page.ResolveUrl and the Calendar Extender in Ajax is causing issues

Similar Question: “The Controls collection cannot be modified because the control contains code blocks” How can I resolve the conflict between Page.ResolveUrl and CalendarExtender in Ajax? An error I encountered is as follows: Server Error in &a ...

Failure to populate AngularJS view

I am a beginner in AngularJS and I am attempting to create a page similar to the example provided here. While the example works perfectly when copied from the link above, I am facing difficulties trying to integrate it into my folder structure as displaye ...

Parent component in Material-ui theme distinguishing itself from child component of the same type

I'm working on customizing the styling of a Material UI Expansion Panel, specifically to apply my theme only to the main parent panel when it is expanded, and not to any nested panels within it. For instance: https://i.sstatic.net/nBhcN.png Here&ap ...

Is there a way to verify if a React hook can be executed without triggering any console errors?

Is there a way to verify if a React hook can be invoked without generating errors in the console? For example, if I attempt: useEffect(() => { try { useState(); } catch {} }) I still receive this error message: Warning: Do not call Hooks i ...

What is the method for retrieving the Java List containing custom class objects defined within the <s:iterator> tag in a JSP file from within my JavaScript function?

Within my jsp file, I am retrieving a List of objects from my java action class (struts2) and displaying them. Now, I need to access these list objects within my javascript method. How can I achieve this? The code in mycode.jsp: <script type="text/jav ...

`Select Dropdown Choice will Populate Corresponding Textfields`

While I know this question has been asked multiple times on Stack Overflow, I am looking for a more tailored solution based on my specific requirements. That is why I'm posting this question. I have an HTML form with PHP that retrieves data from an M ...