Utilizing an object property to set the $maxDistance parameter in a mongodb query for geolocation

Can I create a $near query in MongoDB with a dynamic $maxDistance argument? For instance, I have a collection of fire stations each with a varying coverage radius, and I want to find stations that cover a specific point.

In my collection, the documents follow this structure:

{
    'loc' : [-72,40],
    'radius' : 10
}

An example query would look like:

{'loc': { $near : coordinates, $maxDistance : 'radius'}};

However, this does not work as intended.

If this were a SQL query, it might resemble:

SELECT * FROM table AS foo WHERE foo.radius ... (your distance method)

Is there a way to access the radius variable in a mongo query? Can this be achieved?

Answer №1

It is not possible to base MongoDB queries on values in the collections, as a general rule.

However, since MongoDB 2.4 introduced support for a new index called 2dsphere, it is now possible to store polygons in addition to points in the database. This can be achieved by storing the information in a document like this:

db.so.ensureIndex( { loc: '2dsphere' } );
db.so.insert( {
    name: "Firestation 1",
    loc: {
        type: "Polygon",
        coordinates: [ [ [ 0, 0 ], [ 0, 1 ], [ 1, 1 ], [ 1, 0 ], [ 0, 0 ] ] ]
    }
} );

You can then use an "intersect" query to determine if a point falls within any of the stored polygons:

db.so.find( {
    'loc' : {  
        $geoIntersects: { 
            $geometry: { type: 'Point', coordinates: [ 0, 0 ] } 
        } 
    }
} );

The result of this query will show whether the point falls within a polygon, such as:

{ 
    "_id" : ObjectId("51f24d566775068ab0b786f0"), 
    "name" : "Firestation 1", 
    "loc" : { 
        "type" : "Polygon", 
        "coordinates" : [  [  [  0,  0 ],  [  0,  1 ],  [  1,  1 ],  [  1,  0 ],  [  0,  0 ] ] ] 
    } 
}

To create a circle that is a certain distance away from the centre point, you would need to calculate the polygon points. The mathematics involved may not be simple, but resources like provide examples in JavaScript. By looping through bearings and calculating points along the circumference of the circle, you can construct a polygon with multiple points:

{
    name: "Firestation 1",
    loc: {
        type: "Polygon",
        coordinates: [ [
            [ point1-lon, point1-lat ], 
            [ point2-lon, point2-lat ], 
            [ point3-lon, point3-lat ], 
            ...
            [ point1-lon, point1-lat ], 
        ] ]
    }
}

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 VueJS v-for loop encounters a problem when the values within the array are identical

Check out my pen here: http://codepen.io/leetzorr/pen/aprZqO This is the HTML code: <template v-for="spot in bars" :key="item.$index"> <div id="bar-holder"> <div class="bars"> <ul> <span>{{ $index ...

Steps to remove information from a database using PHP, AJAX, and vanilla JavaScript (without jQuery)

I am facing an issue with deleting data from my database. Whenever I click on the delete button, it deletes the first row instead of the intended row. Below is my PHP code: <?php $connect = mysqli_connect("localhost","root","","abu"); if($conne ...

Saving file with HTML download button results in only HTML document being saved

I am attempting to include a "download file" button on my gatsby website as shown below: <a href="../../images/project-logos/placeholder-company-logo.png" download="test" className="responsive-square project-logo" > <img sr ...

Extracting JSON data from a string using jQuery

http://localhost/project1/index.php //AJAX region $(function(){ $.ajax({ type : 'GET', url : 'https://jsonplaceholder.typicode.com/posts/1', success : function(data){ console.log('success \n', data); }, error ...

Creating image filters using an object in jQuery

I am faced with a challenge where I have multiple image tags nested within a div that has the class google-image-layout. Each image is equipped with various data attributes, including: data-anger="0" data-disgust="0" data-facedetected="0" data-fear="0" da ...

Implement an event listener in a PHP server-side file to capture the onClick event with the

I am completely new to working with Ajax. In my application, I am using ajax along with a server-side php page named Req.php to retrieve records from a database, generate a table based on those fetched records, and then display it. Now, I am looking to inc ...

Require help extracting a JSON object

I am currently working with a JSON database to showcase ingredients on the webpage. For each recipe, I have a dedicated HTML page. To display the ingredients, I am hand typing them into an unordered list on the page. My challenge lies in trying to fetch t ...

Understanding the performance of video in threejs when using getImageData

Edit; Check out the working codepen (you'll need to provide a video file to avoid cross-origin policy) https://codepen.io/bw1984/pen/pezOXm I'm currently trying to adapt the amazing rutt etra example from to utilize video (using threejs), but ...

Tips on modifying the width of grid lines for individual lines

Looking for assistance in adjusting the line width or color of a specific gridline on a Chartjs chart. In this scenario, I am aiming to enhance the grid-line width or alter the color of the horizontal gridline at y-axis 60 exclusively. Despite my efforts ...

Is it possible to retrieve correctly formatted JSON data from this API?

I need help retrieving data from the API located at . When I access the API directly, it returns an array wrapped in <pre></pre> tags, rather than in JSON format. I would like to use an AJAX call to retrieve this data instead of using PHP. Is t ...

Encountering an issue following the installation and integration of an npm module within a Meteor

I recently started a project using the latest version of Meteor. I added a new package by running the command: meteor npm install --save name_of_package Since this package is meant for the client side, I created a file called mypackage.js inside the /cli ...

issue with the emit() and on() functions

While diving into my study of nodejs, I encountered a puzzling issue where emit() and on() were not recognized as functions. Let's take a look at my emitter.js file function Emitter(){ this.events = {}; } Emitter.prototype.on = function(ty ...

Retrieve information from a mysql database based on selected date using the ajax method

To retrieve data from a MySQL database based on the chosen date_time, I need to ensure that the content is seamlessly displayed without any page refresh. After successfully extracting the date_time from the database and showing it on the webpage, my focus ...

What could be causing React to throw an invalid hook error when using useRoutes?

I encountered an error while attempting to add a new route to my project. import React from "react"; import News from "./NewsComponents/News"; import Photos from "./PhotosComponents/Photos"; import Contact from "./Contact"; import Home from "./Home"; ...

Can we accurately pinpoint individual LineSegments in three.js by hovering over them, especially those with unique geometries?

Creating two examples of drawing lines in three.js was quite a fun challenge. One example showcased different geometry and material, while the other kept it simple with just one geometry and material. The demonstration links can be found here: Example 1 an ...

Creating HTML output using an input checkbox in combination with JavaScript

I am creating a dynamic string to be inserted into a div using JavaScript. The issue I am facing involves the onclick attribute of an input checkbox. I want to pass a unique id value with each click of the checkbox. Below is the code snippet I am currently ...

How can I assign the items in a list as keys to an object in redux?

I am currently utilizing Redux in combination with Reactjs. The Redux Documentation states: It's recommended to return new state objects instead of mutating the existing state. My current object's state looks like this: state = [..., {id: 6 ...

Is there a way to secure a document in order to view a specific value and subsequently modify it?

My application allows users to subscribe to events, with a maximum number of participants allowed for each event. When a user books an event, their ID is added to an array within the event document. Once the array reaches its maximum capacity, the user sho ...

Unleashing the power of React: Integrating raw HTML <a href> tags with JavaScript

I am currently working on a small web app that mimics browsing WikiPedia by fetching raw HTML content of WikiPedia articles through its API. I then display this HTML in my app using "dangerouslySetInnerHTML". I am faced with the challenge of enabling a us ...

Troubleshooting random array issues in JavaScript and jQuery

I want to create a randomized array with DOM elements, here's what I have so far: var allTargets=$('#target1, #target2, #target3, #target4'); var randomTargets=null; randomTargets = allTargets[Math.floor(Math.random() * allTargets.length)]; ...