Reputation: 1002
The following part of my function should show the distance between lots of lat/lng coordinates. It works perfect, till the "console.log(dist)
" part below, but I cant get out this values from "dist" to each html "i
".
$(".box").each(function() {
var latlng = $(this).find('.area').data('latlng').split(',');
var lat1 = latlng[0];
var lon1 = latlng[1];
var lat2 = location_lat.toFixed(8);
var lon2 = location_lon.toFixed(8);
distance(lat1, lon1, lat2, lon2, "K"); // <-- start calculate function
function distance(lat1, lon1, lat2, lon2, unit) {
if ((lat1 === lat2) && (lon1 === lon2)) {
return 0;
}
else {
var radlat1 = Math.PI * lat1/180;
var radlat2 = Math.PI * lat2/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);
if (dist > 1) {
dist = 1;
}
dist = Math.acos(dist);
dist = dist * 180/Math.PI;
dist = dist * 60 * 1.1515; // M = statute miles (default)
if (unit === "K") { dist = dist * 1.609344; } // K = kilometers
if (unit === "N") { dist = dist * 0.8684; } // N = nautical miles
console.log(dist); // <-- works perfect, I got all the different values
var display = $(this).find('.area');
$(display).find('i').html(dist.toFixed(0)).append(" <em>km</em>"); // <-- doesn´t work, just empty "i"
}
}
});
I also tried:
...
distance(lat1, lon1, lat2, lon2, "K"); // <-- start calculate function
var display = $(this).find('.area');
$(display).find('i').html(dist.toFixed(0)).append(" <em>km</em>"); // <-- doesn´t work, because "dist" is not defined
... but then "dist" will no longer work (error: disk is not defined). Whats wrong with my ".each
" function? How can I get the values from the "distance function" back to the .each
function part?
Upvotes: 0
Views: 44
Reputation: 338158
Put the distance()
function outside of the loop and let it return the calculated value.
function distance(lat1, lon1, lat2, lon2, unit) {
if (lat1 === lat2 && lon1 === lon2) return 0;
var radlat1 = Math.PI * lat1/180;
var radlat2 = Math.PI * lat2/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);
if (dist > 1) dist = 1;
dist = Math.acos(dist);
dist = dist * 180/Math.PI;
dist = dist * 60 * 1.1515; // M = statute miles (default)
if (unit === "K") { dist = dist * 1.609344; } // K = kilometers
if (unit === "N") { dist = dist * 0.8684; } // N = nautical miles
return dist;
}
$(".box").each(function() {
var latlng = $(this).find('.area').data('latlng').split(',');
var dist = distance(
latlng[0],
latlng[1],
location_lat.toFixed(8),
location_lon.toFixed(8),
"K"
);
$(this).find('.area i').text(dist.toFixed(0)).append(" <em>km</em>");
});
Upvotes: 1