1

I want to show the distance from each list item in miles by doing something like this with the SPAN tag in the below snippet but I am not sure how. The script is sorting fine and calculating the distance already, I just don't know how to write it to the page. I feel like this is fairly simple so I hope someone can help me!

        <li>
            <div class="name">
                Moe Bar <span class="miles"></span></div>
            <div class="long">
                47.60357999999998</div>
            <div class="lat">
                -122.329454</div>
        </li>

Full Code Working example at http://demos.thebeebs.co.uk/bars-in-seattle/

<!DOCTYPE html>
<html>
<head>
    <title>Local Bars</title>
    <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.5.min.js"></script>
    <script>
        function findMe() {
            if (navigator.geolocation != undefined) {
                navigator.geolocation.watchPosition(onFound, onError);
            }
        }
        function onFound(pos) {
            var userLat = pos.coords.latitude;
            var userLong = pos.coords.longitude;
            $('ul li').each(function (index) {
                var locationLat = $(this).find('.lat').html();
                var locationLong = $(this).find('.long').html();
                var distance = getDistance(userLat, locationLat, userLong, locationLong);
                $(this).data("distance", distance);
            })

            reOrder();
        }

        function onError(pos) {
            alert("Something Went wrong");
        }

        function reOrder() {
            $('ul li').sort(sortAlpha).appendTo('ul');
        }

        function sortAlpha(a, b) {
           return $(a).data('distance') > $(b).data('distance') ? 1 : -1;
        };

        function getDistance(lat1, lat2, lon1, lon2) {
            var R = 6371; // km
            var d = Math.acos(Math.sin(lat1) * Math.sin(lat2) +
                  Math.cos(lat1) * Math.cos(lat2) *
                  Math.cos(lon2 - lon1)) * R;
            return d;

        }; 


    </script>
    <style>
        ul .long, ul .lat
        {
            display: none;
        }
    </style>
</head>
<body>
    <div>
        <a href="#" onclick="findMe()">Find Closest Pub</a>
        <ul>
            <li>
                <div class="name">
                    Moe Bar</div>
                <div class="long">
                    47.60357999999998</div>
                <div class="lat">
                    -122.329454</div>
            </li>
            <li>
                <div class="name">
                    Frontier Room</div>
                <div class="long">
                    47.61469022047056</div>
                <div class="lat">
                    -122.34816509008769</div>
            </li>
            <li>
                <div class="name">
                    See Sound</div>
                <div class="long">
                    47.6156159656448</div>
                <div class="lat">
                    -122.32593494177237</div>
            </li>
        </ul>
    </div>
</body>
</html>

1 Answer 1

2

Here is a LIVE working example: http://jsbin.com/ebeyaz/4/edit

Assumption:

In my code, the list is a little easier to code and the explanation assumes this code:

<li data-lat="-122.34928138554072" data-lng="47.61370665587537">
    War Room
</li>

Explanation:

You are sorting using a data attribute that you don't even have it... so, first thing is to append such attribute.

You already have the current Latitude and Longitude, all you need is to calculate the distance between each bar using the navigator.geolocation coordinates and for that, you should update your formula to

// Haversine formula
// http://www.movable-type.co.uk/scripts/latlong.html
function getDistance(lat1, lat2, lon1, lon2) {
  var R = 6371, // km
      dLat = (lat2-lat1).toRad(),
      dLon = (lon2-lon1).toRad();

  lat1 = parseFloat(lat1).toRad();
  lat2 = parseFloat(lat2).toRad();

  var a = Math.sin(dLat/2) * Math.sin(dLat/2) +      
          Math.sin(dLon/2) * Math.sin(dLon/2) *
          Math.cos(lat1) * Math.cos(lat2),
      c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)),
      d = R * c;
  return d;
}

and then, loop through all and create that attribute with the result, for example:

function addDistances(list, geoData)
{
  $(list).each(function() {
    var lat = $(this).data("lat"),
        lng = $(this).data("lng"),
        d = getDistance(lat, geodata.latitude, lng, geodata.longitude),
        km = (Math.floor(d * 100)/100),
        mi = (Math.floor((d*0.621371) * 100)/100);
    $(this)
      .attr("data-distance", d)
      .append(" <span>(" + km + "Km - " + mi + "Miles)</span>");
  });
}

then you can sort normally using what you have.

My output:

enter image description here

4
  • Balexandre,Very nice! Thanks for taking the time. It seems to only work in Chrome though... tried Firefox and Safari with no luck. Any thoughts?
    – echristo66
    Apr 3, 2013 at 21:26
  • yes, I know why... it's assumptions, Chrome does it well, but the others need to be set to understand that the the data type they receive from Google API is json, so we need to use $.ajax instead the short $.get. Example updated.
    – balexandre
    Apr 3, 2013 at 22:36
  • Awesome! You have been very helpful, thanks a million! One last question. If I wanted to NOT ask to share your location on page load and instead wanted to get your location only if you clicked on 'sort by the nearest bars' how would I accomplish that, understanding I would lose the logic regarding 'It seems that you are near...'
    – echristo66
    Apr 4, 2013 at 14:34
  • then you only request the position on that click event. For ex. $(document).delegate('a.show-pos', 'click', function() { requestPosition(); }); where requestPosition would be a simple function requestPosition() {if (navigator.geolocation) navigator.geolocation.getCurrentPosition(success, error); else alert('Your device does not support GeoLocation!'); }
    – balexandre
    Apr 4, 2013 at 16:48

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.