hb8 - 3 months ago 21

Javascript Question

i made a script that gets the geolocation of the user, calculates the distance between the position and items in the object using the Haversine formula, and console.log the distances. My question is how can i console.log only the nearest item ? hope someone can help :)

`<!DOCTYPE html>`

<html>

<head>

<title></title>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

</head>

<body>

<p id="demo"></p>

<script>

var obj = [

{

name:"location1",

lat:60.413750,

long:5.322036

},

{

name:"location2",

lat:59.749054,

long:10.203781

},

{

name:"location3",

lat:59.286271,

long:11.109228

},

{

name: "location4",

lat:59.913869,

long:10.752245

}

];

var x = $("#demo");

var hblat ;

var hblong ;

var distance ;

if (navigator.geolocation) {

navigator.geolocation.getCurrentPosition(showDistance);

} else {

x.html("Geolocation is not supported by this browser.");

}

function showDistance(position) {

hblat = position.coords.latitude;

hblong = position.coords.longitude;

$.each(obj, function(key, value){

distance = hbdistance(hblat, hblong, value.lat, value.long, 'K');

console.log(Math.round(distance*1000)/1000);

});

}

function hbdistance(lat1, lon1, lat2, lon2, unit) {

var radlat1 = Math.PI * lat1/180

var radlat2 = Math.PI * lat2/180

var radlon1 = Math.PI * lon1/180

var radlon2 = Math.PI * lon2/180

var theta = lon1-lon2

var radtheta = Math.PI * theta/180

var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);

dist = Math.acos(dist)

dist = dist * 180/Math.PI

dist = dist * 60 * 1.1515

if (unit=="K") { dist = dist * 1.609344 }

if (unit=="N") { dist = dist * 0.8684 }

return dist

}

</script>

</body>

</html>

Answer

In `showDistance()`

you have an `each`

block where you calculate the distances and that looks right. You're even logging them to console too, so we're almost there.

Let's go with a simple solution here and build up an array of distances:

```
function showDistance(position) {
hblat = position.coords.latitude;
hblong = position.coords.longitude;
var distances = []; // Array to store distances
$.each(obj, function(key, value){
distance = hbdistance(hblat, hblong, value.lat, value.long, 'K');
distances.push(distance); // Add our distance to the array
});
var min = Math.min.apply(Math, distances); // Get minimum value
console.log(min); // Log minimum value
}
```

You can see another SO post which explains obtaining minimum values from arrays here: Obtain smallest value from array in Javascript?

Hope that helps!