Discover the method of utilizing my current location to determine the distance between two points by inputting their latitude and longitude

I'm currently working on customizing my REST API to only retrieve items that fall within a specific radius. I have successfully written the code to calculate the distance between two points and filter out items outside the desired range. However, my current implementation uses a predefined latitude and longitude as the reference point. Is there a way for me to integrate my own location into this algorithm?

app.get('/posts', function(req, res) { 

// Accessing the 'posts' collection from the database
db.collection('posts', function(err, collection) { 

    // Retrieving all documents in the 'posts' collection
    collection.find().toArray(function(err, items) {

        // Array to store filtered documents
        var results = []

//Function for calculating distance between two points.
    function calculateDistance (lat1, lat2, lon1, lon2) {
        var dLat = deg2rad(lat2-lat1);  
        var dLon = deg2rad(lon2-lon1); 
        var a = 
            (Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * 
            Math.sin(dLon/2) * Math.sin(dLon/2))
            ; 
        var c = (2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a))); 
        var d = (6371 * c); // Distance in km
        var e = (d/1.6) //Converting distance in km to miles.
            return e 
    }

        // Iterating over each document and checking the distance criteria
        for (var i = 0; i < items.length; i++) {
            var item = items[i]
             if ((calculateDistance(item.latitude, 43.7035798, item.longitude, -72.2887838) > 25)) {
                 results.push(item)
             }

        }          
        res.send(results);
    });
});
});

Answer №1

To access location information, use navigator.geolocation.

For more information on using geolocation, visit: https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/Using_geolocation

In some browsers like Firefox, a popup may appear asking for permission to share your location. You've likely seen similar prompts when interacting with websites that utilize the Google Maps API.

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

The Splice function is malfunctioning due to issues with the object (the indexOf function is not recognized)

I am currently dealing with an object that looks like this: Object {val1: "Hello", val2: "", dt1: "pilo1", dt2: "pilo2", lo1: "log1"} My goal is to remove any keys within the object that have empty values (""). I attempted the following code snippet: ...

The AJAX status is now 0, with a ready state of 4

Struggling to execute an AJAX call (using only JavaScript) to store a user in the database. The JavaScript file I am working with includes this code: var url = "interfata_db.php"; xmlhttp.onreadystatechange = function(){ alert('ready state &apos ...

Manage the dimensions of elements using Javascript on the client side

Here is a form I created: <form action="#" enctype="multipart/form-data" method="post" name="..." id="formPhoto" class="fmp"> <input type="file" name="pho" id="photo" class="inph" accept="image/*"> <button type="submit" id=" ...

"Creating multiple circles on an HTML5 canvas using an iPad: A step-by-step guide

My current code is only drawing one circle at a time on an iPad view, but I want to be able to draw multiple circles simultaneously. How can I achieve this? // Setting up touch events for drawing circles var canvas = document.getElementById('pain ...

Tips for Dynamic Importing and Rendering of Components in ReactJS

I'm looking to dynamically import and render a component in React. I have two components - Dashboard and Home. Essentially, I want to dynamically render the Dashboard Component inside the Home Component without having to import it beforehand or maybe ...

Exploring the World of Next.js and Sequelize Model Relationships

Greetings to all the problem-solving enthusiasts out there! I'm currently in the process of revamping a previous project using Next.js, and I've hit a roadblock that has me stumped. My current challenge involves establishing an association betwe ...

Using C# and AJAX to refresh the view with the latest model data

In my .NET web app, I have a process that involves navigating from Page A to Page B where I input a barcode scan result. Page B then displays a table generated by various queries and data inserted into a view model. What I am seeking is the ability to rep ...

jQuery form validation issue, unresponsive behavior

<!DOCTYPE html> <html> <head> <title> jquery validation </title> </head> <body> <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js" type="text/javascript"> ...

An error occurs due to attempting to parse the data using JSON.parse

Trying to troubleshoot a seemingly simple issue: The callback function of an AJAX post request is receiving a JSON string in the 'data' parameter. {"result":"Torte"} Manually parsing it yields the expected result: var response = JSON.parse(&ap ...

Using .setTimeout() to iterate over a for loop for updating data in MongoDB

My goal is to have the "Bee" sleep for 5 seconds when its energy reaches 0, and then regain all its stats. However, even though the stats become 0 after the command is executed, they do not return after 5 seconds. Any suggestions on how to fix this? // som ...

What is the location where nvm saves its node.js installations?

I'm having trouble locating where node.js installations are stored after downloading and installing through commands like: nvm install 5.0 Can anyone provide some insight on this? ...

Aligning a div between the page margins with a single click

I am attempting to compile a list of products with a concealed div inside. Upon clicking on the product, the hidden div should reveal and display details. If you inspect the fiddle, you'll notice that the final hidden div protrudes beyond the margins ...

How do I utilize the file handler to execute the flush method within the Deno log module using Typescript?

I'm having trouble accessing the fileHandler object from my logger in order to flush the buffer to the file. This is the program I am working with: import * as log from "https://deno.land/<a href="/cdn-cgi/l/email-protection" class="__cf_emai ...

The AJAX response enters a continuous loop if it contains the window.print function

I'm looking to print the screen upon receiving an ajax response. Here's my code snippet: function initiatePrint() { var request = new XMLHttpRequest(); request .open("GET", "printPage.html", true); var counter = 0; ...

Is there a way to retrieve the transaction specifics for the initial 50 clients from a MongoDB database?

In my PC's local server, there is a cluster with approximately 240,000 entries of transaction data. The abbreviation Cust_ID represents Customer ID. https://i.sstatic.net/5g65l.png Each file contains transactions made by different customers, with a ...

The excessive offset of pixels is causing the popup dialog to appear misaligned

I'm having an issue with my modal popups where the dialog is rendering 200px to the left and about 100px above its intended position. Just updated jQuery. DevicesRightClickActionsMenuController.prototype.showActionsMenu = function(event) { right ...

Facebook and the act of liking go hand in hand, growing together

I am working on a website where I want to include Facebook like and share buttons with counters. To achieve this, I used Facebook's own links to generate these buttons for the specific URL. The issue I encountered is that when I like or share the page ...

Emphasize the importance of paying attention to read-only

Currently, I have a form containing three inputs. The last input has the property of being ‘readonly’, as the user is supposed to fill it by clicking buttons (such as a virtual keyboard) rather than typing manually. Everything functions correctly in th ...

Angular request accessing CoinMarketCap API

Currently, I am immersing myself in the world of the latest CoinMarketCap API and navigating through the waters of data. The Node.js example below demonstrates how to make a request. But how can I achieve the same in Angular? Any tips or suggestions would ...

Having trouble with my nodejs backend when trying to choose collections

In my primary app.js file, I establish the mongodb connection to my mlab database. const mongo = require('mongodb').MongoClient; const express = require('express'); const path = require('path'); const bodyParser = require(&ap ...