Ways to access specific elements of an array through filtering

I am currently working on a script that compares the coordinates from the browser with coordinates in an array. However, I am encountering an issue where the const 'matchgeosucursal' returns as 'undefined' even when I force the filter condition to match. The main objective of this code is to retrieve the URL associated with the matching scenario, and I believe there may be an error in how I'm using the filter function.

//Request permissions
$( document ).ready(function getLocation() {
  
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(showPosition);
    } else { 
      console.log ("Geolocation is not supported by this browser.");
    }

    
//Filter and gets match url

function showPosition(position) {  
  console.log("Latitude: " + position.coords.latitude)
  console.log("Longitude: " + position.coords.longitude);
  var navlat = position.coords.latitude; //Browser lat
  var navlon = position.coords.longitude; // Browser lon

  // Array
  var sucursales = [
    {lat: 21.924089, lon: -102.293378, url: "https://shorturl.at/test1"},
    {lat: 21.859964, lon: -102.298034, url: "https://shorturl.at/test2"},
    {lat: 32.45569, lon: -116.836181,  url: "https://shorturl.at/test3"},
    {lat: 24.114868, lon: -110.340389, url: "https://shorturl.at/test4"},
    {lat: 21.0335386, lon: -89.559187, url: "https://shorturl.at/test5"}];
  
//Match result
  const matchgeosucursal = sucursales.filter( sucursales =>  sucursales.lat === navlat && sucursales.lon === navlon);
  console.log('Match> ' + matchgeosucursal);

       
 }

});

Answer №1

Everything is functioning properly, except for the fact that console.log isn't displaying objects correctly. During my testing, I utilized console.table and everything appeared accurate:

Note: I defined position as a const since I couldn't extract coordinates from a document like you did. Nonetheless, it should function as long as the values for position.coords.latitude and ...longitude are correct.

const position = {
  coords: {
    latitude: 21.0335386,
    longitude: -89.559187,
  }
}

function showPosition(position) {
  console.log("Latitude: " + position.coords.latitude)
  console.log("Longitude: " + position.coords.longitude);
  var navlat = position.coords.latitude; //Browser lat
  var navlon = position.coords.longitude; // Browser lon

  // Array
  var branches = [
    {lat: 21.924089, lon: -102.293378, url: "https://shorturl.at/test1"},
    {lat: 21.859964, lon: -102.298034, url: "https://shorturl.at/test2"},
    {lat: 32.45569, lon: -116.836181,  url: "https://shorturl.at/test3"},
    {lat: 24.114868, lon: -110.340389, url: "https://shorturl.at/test4"},
    {lat: 21.0335386, lon: -89.559187, url: "https://shorturl.at/test5"}];

//Matching result
  const matchedBranch = branches.filter( branch =>  branch.lat === navlat && branch.lon === navlon);
  console.log("Match:")
  console.table( matchedBranch);


 }


showPosition(position)

Answer №2

It seems that the issue you are encountering is due to the fact that your filter is searching for an exact match of latitude and longitude, and the user's geolocation may not be precise enough to meet these exact coordinates.

To improve accuracy, you could consider checking if the user's latitude and longitude fall within a specified range, like this:

const matchedLocations = locations.filter( location =>
            location.lat >= (userLat - 0.005) &&
            location.lat <= (userLat + 0.005) &&
            location.lon >= (userLon - 0.005) &&
            location.lon <= (userLon + 0.005));

This approach would provide accuracy within approximately half a mile. Of course, you can adjust the range as needed based on your specific requirements.

//Accessing Geolocation
$( document ).ready(function getLocation() {

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else {
        console.log ("Geolocation is not supported by this browser.");
    }


//Filter and Retrieve Matching URL

    function showPosition(position) {
        console.log("Latitude: " + position.coords.latitude)
        console.log("Longitude: " + position.coords.longitude);
        var userLat = position.coords.latitude; //User's latitude
        var userLon = position.coords.longitude; // User's longitude

        // Location Array
        var locations = [
            {lat: 21.924089, lon: -102.293378, url: "https://shorturl.at/test1"},
            {lat: 21.859964, lon: -102.298034, url: "https://shorturl.at/test2"},
            {lat: 32.45569, lon: -116.836181,  url: "https://shorturl.at/test3"},
            {lat: 24.114868, lon: -110.340389, url: "https://shorturl.at/test4"},
            {lat: 21.0335386, lon: -89.559187, url: "https://shorturl.at/test5"}];

//Matching Result
        const matchedLocations = locations.filter( location =>
            location.lat >= (userLat - 0.005) &&
            location.lat <= (userLat + 0.005) &&
            location.lon >= (userLon - 0.005) &&
            location.lon <= (userLon + 0.005));
        
        console.log('Matched Location > \nlat: ' + matchedLocations[0].lat +"\nlon: " + matchedLocations[0].lon + "\nurl: " + matchedLocations[0].url);


    }

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

Creating a seamless scrolling experience with a designated stopping point - here's how to achieve it!

I understand how to implement a scroll effect on an element with a specific class or ID. However, I am unsure of how to make the scrolling stop 20px above that element. I have seen examples using document.getElementById() to achieve this: function scr ...

Using Socket.io in conjunction with the MEAN stack: A beginner's guide

I'm struggling to figure out how to integrate Socket.io with MEAN stack. Although I am able to run it in the latest version without any errors using the following code: var server = app.listen(config.port, config.hostname); io = io.listen(server); H ...

What steps can I take to incorporate validations in the code so that it can correctly show errors like 'Password is too short' and 'Height is not a valid number'?

I need to update the checkSubmit() function to display the following messages: Passwords do not match Password is too short (minimum 4 characters) Height is not numeric I have successfully implemented the first check, but I am unsure how to approach the ...

Loop through an array of objects that each contain two sub-objects using ng

I'm looking to organize each data-record in an object that contains two other objects structured like this: data Object { abbData={...}, invoiceData={...}} abbData Object { service="24", conn_fee="0", month_fee="249", more...} invoiceData ...

Traverse through an array based on a specified numerical index

If I only have the index of a specific item in an array, I want to be able to retrieve its key value. For instance, from the given array, I would like to get just the value 3. Additionally, it would be helpful to obtain the previous and next IDs as well. ...

Using JavaScript to retrieve and compare element values for a total sum

Given two arrays, the goal is to determine if any two numbers in the array add up to 9. The function should return either true or false. For example: array1 [1, 2, 4, 9] has no pair that sums up to 9, so it returns false array2 [1, 2, 4, 5] does have a ...

The passage of time becomes distorted after a few hours of using setInterval

I created a simple digital clock using JavaScript to show the time on a TV screen. However, after several hours of running, I noticed that the displayed time gets off by a few seconds (around 30 or more). Below is the code snippet I used: getTime() { ...

What is the most effective method to activate the Facebook pixel in VueJS?

UPDATE WITH CORRECT CODE: <script> export default { mounted() { // this.comments_data = this.comments; }, props: ['type'], data() { return { // ...

Trigger offcanvas modal and backdrop simultaneously using Bootstrap v5.0

Working with Bootstrap v5.0 offcanvas has been smooth sailing until I hit a roadblock. Clicking on the offcanvas button seems to be triggering both the offcanvas-backdrop and modal-backdrop divs simultaneously. <div class="modal-backdrop fade show ...

Navigating through intricate HTML structures with JavaScript can be challenging

Snippet of 01.js code: var childElements = document.getElementById('selected-plays').getElementsByTagName('li'); function getRequiredElements(childElements) { var listItems = []; var i = 0; for(i = 0 ; i < childElements. ...

JavaScript / Ajax / PHP - A Minor Bug That's Bugging Me

I'm in need of some help, as I feel like I'm losing my mind right now. I've developed a code using php/js/ajax to verify if an email address exists when it's submitted. After testing the ajax, I can confirm that the correct values are ...

Find a user in the database using Sequelize by providing two search parameters

Is there a way to use the users.findOne method with two parameters similar to the example shown below, instead of just using either the id or name individually? const user = await Tags.findOne({ where: { id: ID, name: NAME }, }); ...

Customizing the select form arrow in Bootstrap 4: A step-by-step guide

I'm currently working on a form using Bootstrap 4 and I want to customize the style of the arrow select element. I'd like it to look like the second version shown below: https://i.sstatic.net/oUBBI.png I've tried various methods (reference ...

Displaying a group of elements in ReactJS

I'm currently working on assembling an array using different JSX components. There's a function I've created that populates this array with components and then returns it. let components = []; switch (obj.type) { case 'title': ...

Pause the setInterval function on hover and continue when mouse is moved away

I'm encountering an issue while trying to tweak some code I already have. My goal is to stop the setInterval function when the mouse hovers over div id "mine" and then resume it when the mouse moves away from the div. Despite my efforts throughout the ...

Extract attributes from a string of HTML containing name-value pairs

Here is a sample string that I need to work with '<img id="1" data-name="test" src="img_01.jpg" />' My goal is to extract the attribute name and value pairs from the string, create the element, and apply these attributes. I have come up ...

Certain browsers may not trigger the onsubmit event of an HTML form when a hidden submit button and readonly input are involved

Currently, I am in the process of creating a form that should trigger the onsubmit event when the "Enter" key on the keyboard is pressed. However, I have encountered an issue where the event does not fire on certain browsers, depending on the form fields p ...

What is the process for making changes to a document in Mongoose?

My goal is to allow users to update existing mongoose documents using a form with method-override package. Despite trying various solutions found on Stackoverflow, I have not been able to resolve my issue. The desired functionality is for the user to view ...

Creating custom elements for the header bar in Ionic can easily be accomplished by adding your own unique design elements to the header bar or

I'm a beginner with Ionic and I'm looking to customize the items on the header bar. It appears that the header bar is created by the framework within the ion-nav-bar element. <ion-nav-bar class="bar-positive"> <ion-nav-back-button> ...

Avoiding superfluous API calls with Redux thunk - how can you do it?

My action.js file contains the following code: import axios from 'axios'; export const SEARCH_TERM = 'SEARCH_TERM'; export const SAVE_SEARCH = 'SAVE_SEARCH'; export function search(query) { const githubApi = `https://api. ...