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