Locate the closest coordinate using Meteor/Mongo through manual search

After utilizing the $near command to fetch a list of cities near my current coordinates, I realized that there is an issue. It seems that you can be on the outskirts of a large city but still be closer to the center of the neighboring city than to where you are currently located. To address this, I am interested in incorporating population data into the results to accurately determine city size.

Villages.find({loc: {$near: [lat,long], $maxDistance: 2}}, 
                     {fields: {name: 1, _id: 0}}, 
                     {limit: 1}
                     );

Since it doesn't seem feasible to achieve this using $near, I'm considering manually selecting the nearest cities and factoring in their populations. Would appreciate guidance on how best to approach this task, possibly by implementing haversine or other methods for accurate results?

Answer №1

Testing this out will be beneficial. Your code has a small technical mistake that might be causing the issue:

 Villages.find({loc: {$near: [long,lat], $maxDistance: 2}}, 
                 {fields: {name: 1, _id: 0}}, 
                 {limit: 1}
                 );

In MongoDB, the order should be long, lat instead of lat, long. It's also important to note that this syntax is outdated and the preferred way now is:

loc: { $near : {
            $geometry : [long, lat],
            $maxDistance : 2
        } }

The structure for loc should resemble this:

loc: {
    type : "Point",
    coordinates : [ long , lat ]
}

Don't forget to create an index for them as well:

MyCollection._ensureIndex({"loc" : "2dsphere"});

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 first three AJAX requests are successful, but the fourth one fails to reach the PHP script

I am currently working on cascaded selects (a total of 4) that retrieve data from a database. To populate them, I use SQL queries based on the selection made in the previous select element. To establish communication between the select element and the subs ...

Creating a project that utilizes Bing Translate and the Node.js programming language

As I work on developing a web application that enables users to translate text using the Bing translator API, I am facing an issue. I attempted to execute a translator.js file via a script tag, but encountered a roadblock since Node.js code cannot be run t ...

Is there a way to alter the format of a URL?

I'm utilizing the ytdl-core library to access a URL for audio content. The provided URL is: https://r2---sn-gwpa-w5py.googlevideo.com/videoplayback?expire=1612552132&ei=ZEMdYNnJDumPz7sPyrSLmAw&ip=49.36.246.217&id=o-AFQLS1cSUJ6_bXBjMOIiWk1N ...

I'm not satisfied with the value of the ReactJs state after the change

I am working on creating a calendar app for practice purposes. Currently, I have a current_month state variable set to 1. Additionally, I have a function called IncreaseMonth() that is designed to increment the value of current_month. However, when the va ...

Is there a versatile Node.js HTTP request module that is compatible with both server-side and browser-side development, particularly when packaged with Webpack?

Currently, I am searching for a request module that can operate seamlessly in both the Node.js server and the client when compiled with Webpack. The requirements are quite straightforward. I simply need to execute some basic HTTP Ajax requests such as get ...

How can I implement a loop using .then in JavaScript?

Looking to understand the .then concept in JavaScript, I am curious if it is feasible to generate a series of .then's using a for loop. request.send(myRequest) .then(r => console.log(r, 0)) .then(r => console.log(r, 1)) .then(r => ...

Exploring the Concept of Dependency Injection in Angular 2

Below is a code snippet showcasing Angular 2/Typescript integration: @Component({ ... : ... providers: [MyService] }) export class MyComponent{ constructor(private _myService : MyService){ } someFunction(){ this._mySer ...

MongoDB: The art of crafting subqueries in MongoDB

{ "_id" : ObjectId("55115e69288dbca12d2ed079"), "gameId" : "acadcf1a-b557-4ef9-ab3b-636e1f7f909f", "sportName" : "NCAAMB", "scheduleType" : "days", "status" : "closed",//enumeration : Inprogress, completed,closed "scheduledOn" : ISO ...

NG0303: Unable to establish a connection with 'ngbTooltip' as it is not recognized as a valid property of 'button'

ERROR: 'NG0303: Can't bind to 'ngbTooltip' since it isn't a known property of 'button'.' Encountering this issue in my Angular 12 project when running local tests, the ngbTooltip error is present in all .spec files. ...

What steps can be taken to stop 'type-hacking'?

Imagine owning a popular social media platform and wanting to integrate an iframe for user signups through third-party sites, similar to Facebook's 'like this' iframes. However, you are concerned about the security risks associated with ifra ...

Issue found: MongoDB version 2.4.8 is causing excessive memory consumption due to capped collection and tailable cursor

We have recently started delving into the world of Capped Collections and Tailable Cursors in MongoDB to develop a notification queue system. However, during a simple LinqPad test (code provided below), we observed that MongoDB continuously allocates memor ...

Step-by-step guide on activating a button only when all form fields are validated

My very first Angular 5 project. I've gone through resources like: https://angular.io/guide/form-validation and various search results I looked up, only to realize that they are all outdated. In my form, I have several input fields such as: <for ...

Set up a single array containing multiple objects in a table, each with its own unique set of keys

I am currently developing an application that retrieves data from one or multiple databases, each with different names and varying numbers of columns. The goal is to consolidate this data into a single report screen and export it as a table. While the tabl ...

Any tips on silencing webpack's constant nagging about the "Critical dependency: require function is used in a way..." warning message?

My immediate goal is to resolve this warning. However, it seems that a different approach may be necessary. I have developed an npm library for date/time functions with most of the code being general-purpose and compatible with both Node.js and web browse ...

Retrieving information from an Express.js API using React.js. Postman requests are successfully communicating with the API

Hey there, I'm facing a little issue and could use some help. I have an Express application that is working perfectly with requests from Postman (adding, deleting, etc.). Now, I want to connect my client side (React.js) with the existing API using the ...

Do not use the .map method! Caution: Every child component in a list must be assigned a unique "key" prop

I have recently started working with NEXT JS and I am encountering a peculiar issue for which I haven't been able to find a solution online. The warning message I'm getting is: "Each child in a list should have a unique key prop." Warning: Each c ...

"Removing an item from an array stored in localstorage: A step-by-step guide

I need to remove an object from an array and also delete it from local storage. I have attempted to use the splice method but am struggling with how to implement it correctly. Below is the code that I have tried: var details = []; function addEntry() ...

What is the best way to create an impact?

Need help fixing the parallax effect on this page. I attempted to implement a parallax effect but encountered some issues. Here is the JavaScript code: $objWindow = $(window); $('section[data-type="background"]').each(function(){ var $bgOb ...

Error encountered while downloading file from S3 on NextJs due to network issue

I have encountered a network error while trying to download a file from Amazon S3. Despite configuring my Amazon config file correctly and using the S3.getObjectURl() method for the download, it still fails. Below is the snippet of my code: const AWSDownlo ...

Is there a method by which I can access information from a linked document in Firebase?

I am relatively new to firebase and I am attempting to retrieve data from a referenced document in another collection to display. Link 1 Link 2 This is how I add a student and the parent's ID: const newStudent = { name: req.body.name, grade: ...