Trouble organizing a collection of destinations based on their geolocation and proximity

To address this issue, my approach has been to feed variables into the value attributes of an option list and then sort it based on these values. When manually assigning values, everything works smoothly, for example:

<option id="link1" value="1">A</option>

However, I am struggling to determine how to assign each option a calculated distance from my current location and then sort them accordingly.

The following code snippet aims to provide clarity on this problem:

const navToSelection = _ => {
  const el = document.getElementById("panel_link_library")
  const val = el.options[el.selectedIndex].id
  window.location.href = val // That's it!
}
$("#panel_link_library").html($("#panel_link_library option").sort(function(a, b) {
  return parseInt($(a).val()) == parseInt($(b).val()) ? 0 : parseInt($(a).val()) < parseInt($(b).val()) ? -1 : 1;
}));

function distance(lon1, lat1, lon2, lat2) {
  var R = 6371; // Radius of the earth in km
  var dLat = (lat2 - lat1).toRad(); // Javascript functions in radians
  var dLon = (lon2 - lon1).toRad();
  var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
    Math.sin(dLon / 2) * Math.sin(dLon / 2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  var d = R * c; // Distance in km
  return d;
}

/** Converts numeric degrees to radians */
if (typeof(Number.prototype.toRad) === "undefined") {
  Number.prototype.toRad = function() {
    return this * Math.PI / 180;
  }
}

var test_1 = window.navigator.geolocation.getCurrentPosition(function(pos_1) {
  console.log(pos_1);
  console.log(
    distance(pos_1.coords.longitude, pos_1.coords.latitude, 42.37, 71.03)
  );
  return pos_1
});

var test_2 = window.navigator.geolocation.getCurrentPosition(function(pos_2) {
  console.log(pos_2);
  console.log(
    distance(pos_2.coords.longitude, pos_2.coords.latitude, 33.37, 71.03)
  );
  return pos_2
});
<script src="https://cdn.bootcss.com/jquery/1.11.1/jquery.min.js"></script>


<div class="parent_mob">
  <div>
    <div>
      <select class="panel_link_button_2" id="panel_link_library" name="p_links">
        <option id="panel_link_library" value="">Choose a location</option>
        <option id="link1" value="test_1">A</option>
        <option id="link2" value="test_2">B</option>
    </select>
    </div>
  </div>
  <div>
    <div id="abc" class="panel_link_button" onclick="navToSelection()">Place a Pickup Order</div>
  </div>
</div>

I suspect that there may be an issue with

Answer №1

After making some adjustments to the code, I tested it on my PC and it seems to be working fine. To test it yourself, avoid using the snippet here as it may not work properly. Instead, copy all the code below, paste it into an HTML file on your own computer, and then try running it.

<html>
<head>
<script src="https://cdn.bootcss.com/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>

<div class="parent_mob">   
<div >
  <div>
    <select class="panel_link_button_2" id="panel_link_library" name="p_links">
        <option id="panel_link_library" value="">Choose a location</option>
        <option id="link1" value="test_1">A</option>
        <option id="link2" value="test_2">B</option>
    </select>
</div>
</div>
<div>
 <div id="abc" class="panel_link_button" onclick="navToSelection()">Place a Pickup Order</div>
 </div>
</div> 

...
(remaining code omitted for brevity)
...

</body>
</html>

Answer №2

The solution provided successfully achieves the intended outcome, although through a workaround method. While it may not execute in the snippet tool, running this code on your local machine or server should yield the desired results:

<html>
<head>
<script src="https://cdn.bootcss.com/jquery/1.11.1/jquery.min.js">
  
  </script>
   
  



</head>
<body>

<div class="parent_mob">   
<div >
  <div>
    <select class="panel_link_button_2" id="panel_link_library" name="p_links">
      <option id="panel_link_library" value="0">Choose a location</option>
      <option id="link2" >B</option>
      <option id="link1" >A</option> 
       <option id="link3" >C</option> 
       <option id="link4" >D</option> 
       <option id="link5" >E</option> 
    </select>
</div>
</div>
<div>
 <div id="abc" class="panel_link_button" onclick="navToSelection()">Place a Pickup Order</div>
 </div>
</div> 
  
  
  
    <script>
  
  const navToSelection = _ => {
  const el = document.getElementById("panel_link_library")
  const val = el.options[el.selectedIndex].id
  window.location.href = val // That's it!
}

</script>

<script>

function distance(lon1, lat1, lon2, lat2) {
  var R = 6371; // Radius of the earth in km
  var dLat = (lat2-lat1).toRad();  // Javascript functions in radians
  var dLon = (lon2-lon1).toRad(); 
  var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
          Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * 
          Math.sin(dLon/2) * Math.sin(dLon/2); 
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
  var d = R * c; // Distance in km
//  console.log("navigator.geolocation d "+d);
  return d;
  
}

/** Converts numeric degrees to radians */
if (typeof(Number.prototype.toRad) === "undefined") {
  Number.prototype.toRad = function() {
    return this * Math.PI / 180;
  }
}



 
 window.navigator.geolocation.getCurrentPosition(function(pos_1) { 
   console.log("navigator.geolocation start ");
  document.getElementById('link1').value = distance(pos_1.coords.longitude, pos_1.coords.latitude, 35.43,-120.34);
   console.log(pos_1.coords.longitude);
   console.log(pos_1.coords.latitude)
  document.getElementById('link2').value = distance(pos_1.coords.longitude, pos_1.coords.latitude, 35.43,-119.23);
   document.getElementById('link3').value = distance(pos_1.coords.longitude, pos_1.coords.latitude, 35.22,-118.32);
   document.getElementById('link4').value = distance(pos_1.coords.longitude, pos_1.coords.latitude, 34.06,-118.22);
   document.getElementById('link5').value = distance(pos_1.coords.longitude, pos_1.coords.latitude, 33.98,-118.44);
  
   $("#panel_link_library").html($("#panel_link_library option").sort(function (a,b) {
    
 
    return parseInt($(a).val()) == parseInt($(b).val()) ? 0 : parseInt($(a).val()) < parseInt($(b).val()) ? -1 : 1; 
  
 
}));
document.getElementById("panel_link_library").selectedIndex = "0";
});



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

Is it possible for Angular to retrieve information from one JSON file but not another?

After updating the names in the code to reflect the current ones, I would greatly appreciate any help or suggestions! The json file has been provided, so there's not much additional setup required. Just a heads up: I haven't created a service fi ...

JavaScript Audio working on local machine but not on server due to HTML5 compatibility issues

For my project, I am utilizing audio and Javascript in the following way: To start, I populate an array with audio files: var soundArray = new Array(); for (i=0; i<6; i++) { soundArray[i] = new Audio('sounds/sound_' + i + audioExt); ...

Show a selected checkbox within a form for submitting via POST method

I am in need of assistance with a wizard that should display the previously posted value. index.html <form method="post" action="posted.php"> <input type="text" name="surname" value="" placeholder="Surname" /> <input type="text" name="firs ...

Transferring JSON data from Django for visualization on a D3 graph

I'm currently working on customizing a D3 bar graph found at http://bl.ocks.org/3885304 to accommodate JSON data from Django. In Django, I have a variable that holds JSON formatted data like this: [{"score": 1, "color": "blue"}, {"score": 5, "color": ...

I am having trouble locating the lightbox and bootstrap js file in Django. Any suggestions on how to resolve this issue would

[11/Nov/2020 20:13:11] "GET /about HTTP/1.1" 200 3615 [11/Nov/2020 20:13:12] "GET /static/js/lighbox.min.js HTTP/1.1" 404 1677 [11/Nov/2020 20:13:12] "GET /static/js/bootstrap.bundle.min.js.map HTTP/1.1" 404 1716 A snippet fr ...

The code will only detect the browser when accessed from a mobile device, and will display a

I've experimented with various methods to make this work. My website has a streaming radio player at the top of the page, usually using the default script provided: <center> <!--Wavestreaming.com SHOUTcast Flash Player--> <scri ...

Trouble updating Kendo DropDown in Internet Explorer

Having an issue with updating a Kendo DropDownList through a javascript function. It works fine in FireFox and Chrome, but not in Internet Explorer. @(Html.Kendo().DropDownList() .Name("myDDL") .HtmlAttributes(new { style = "width: 320px" }) . ...

Error: The last line is missing a trailing comma

I'm struggling to understand why my tslint insists on having a trailing comma at the end of the last line in the objects. Is there a way to configure the ignore rule for the last line of objects? Appreciate any help! For example: settings = { ...

I am experiencing issues with the functionality of the Search Button in my code

I am experiencing an issue with the Search Button in my Search Form. I created the Search form using only html and pure CSS to test whether JS is necessary for a Search form with Drop Down Filter! Do I need to incorporate some JS code or is it feasible to ...

Incorporate videos from platforms like Youtube, Vimeo, and more

I am looking to add videos to my website without hosting them on my server. I want the flexibility to use links from any source, not just YouTube or Vimeo. Is there a way to achieve this using something similar to an iframe? <iframe width="560" heigh ...

Unexpected behavior in Next.js when using Auth0: pageProps are empty when wrapped with withPageAuthRequired HOC

Explaining the Issue The problem arises when using withPageAuthRequired with getServerSideProps, as the pageProps object is empty. Despite following common practices, the pageProps parameter remains undefined. Expected Outcome Upon calling getServerSideP ...

Interactive Bootstrap Modals

Is it possible to create a "page" viewing experience within a bootstrap modal? This type of user interface flow is common in many mobile apps, but after reviewing Bootstrap's components, I'm unsure how to implement this or if it's even supp ...

In which situations is it required to specify the return type of a function in TypeScript?

When it comes to making functions in typescript, the language can often infer the return type automatically. Take for instance this basic function: function calculateProduct(x: number, y: number) { return x * y; } However, there are scenarios where dec ...

Once the AJAX callback is complete, the onblur event will revert back to the original field or the updated field

I am currently working with an AJAX callback: Here is the HTML snippet: <a onCLick="loadXMLDoc(id1,id2)">(Add)</a> This function triggers an AJAX method that replaces the "(Add)" text with a basic HTML input field. Subsequently, when there ...

Searching through the Symfony2 database with the help of Select2 and Ajax

Currently, my FAQ System is running smoothly. However, I am looking to enhance it by adding a search function using Select2. Here's what I have so far: Select2 AJAX Script <script> $("#searchall").select2({ ajax: { ...

Tips for adding transparent images (such as logos) to an HTML website: I'm struggling with getting rid of the white background that appears on the website. Does anyone know how

Seeking guidance as a beginner web developer. I am currently working on adding a transparent logo to my website, but the white background is showing up behind the logo. How can I fix this issue? Here is the link to the image - Here is the HTML & ...

JavaScript failing to render AJAX request

I have a website that utilizes AJAX to fetch data in JSON format from the backend and then displays it on the page. The website is built using MVC .NET framework. Below is the function responsible for loading events from the backend: function initEvents( ...

AJAX: Learn how to execute an AJAX call using a JavaScript function

Is there a method to determine (using developer tools like Chrome, Firefox, Opera, etc) the most recent function that triggers an AJAX call? This could be helpful for debugging web applications. Appreciate your help ...

PHP - Issue with AJAX Login Functionality

I have been developing an AJAX login system and encountering an issue where it does not send any response back unless I use exit("error here") in the script. However, my goal is to return a JSON response instead. The form structure: <div id="account" ...

Integrating Bootstrap-vue into your Webpack setup for seamless usage

After beginning a project with vuejs-templates and webpack, I decided to incorporate bootstrap-vue. Now, the challenge is figuring out how to implement a bootstrap button. In my code base, specifically in main.js, I have imported BootstrapVue: import Vu ...