0

I have an array which is produced on the success event of an ajax request. The array obtained from the ajax request looks like this:

Array:

            [{
                "locationID": "9",
                "locationName": "Employee Residence",
                "locationLatitude": "34.47189",
                "locationLongitude": "-111.9896046999",
            }, {
                "locationID": "40",
                "locationName": "Tron Utah",
                "locationLatitude": "33.964212",
                "locationLongitude": "-118.3783589999",

            }, {
                "locationID": "39",
                "locationName": "Tron Enterprises",
                "locationLatitude": "33.735187",
                "locationLongitude": "-111.9579499999",

            }]

Calculations are performed on this array which provides a list of locations and their distance from the users current location. I would like to sort the results by distance; my code is as follows:

Jquery:

// Success
success: function (data) {
    // Obtain Log/Lat
    navigator.geolocation.getCurrentPosition(function(position) {
        // Obtain Current Position Lat/Lon
        glbVar.latitude = position.coords.latitude;
        glbVar.longitude = position.coords.longitude;
        // Console Log
        //console.log('Lat: ' + glbVar.latitude + ' Lon: ' + glbVar.longitude);
        // Index Location Return Data
        for (var index = 0; index < data.length; index++) {
            // Items
            var item = data[index];
            // Obtain Location Details
            varLocationDetails[index] = {"Location Position": {"Longitude": item.locationLongitude, "Latitude": item.locationLatitude, "Location": item.locationName}};
            // Each Location Detail
            $.each(varLocationDetails[index], function (a,b) {
                // Each Locations Distance (From Users Current Location)
                varLocationsDistance = calculateDistance(glbVar.longitude, glbVar.latitude, b.Longitude, b.Latitude);
                // Determine Locations Radius
                if (varLocationsDistance <= varLocationRadius) {
                    // Determine Distance For Each Location
                    varDistanceObject[varInt] = {distance: varLocationsDistance, location: b.Location};
                    // Sort by Distance
                    //varDistanceObject[varInt].sort(function(a,b) {
                    //  return parseInt(a.distance) - parseInt(b.distance)
                    //});
                    // Console Log
                    //console.log(varDistanceObject[varInt]);
                    // Obtain Location Name/Distance
                    varLocation = b.Location;
                    varDistance = calculateDistance(glbVar.longitude, glbVar.latitude, b.Longitude, b.Latitude);
                    // Obtain Function Return
                    functionReturn = '<li>' + varLocation + ': ' + varDistance + 'm</li>';
                    // Console Log
                    //console.log(functionReturn);
                    // Function Return
                    $('#groups').append(functionReturn);// Append to HTML
                };
                // Increment
                ++varInt;
            });
        }
    });
}

Distance Calculation

            // Calculate Distance
            function calculateDistance(varLongitude, varLatitude, varLon, varLat) {
                // Assign Radius
                varRadius = 6371;
                // Obtain Lon/Lat Values
                varLongitude = varLongitude * (Math.PI / 180);
                varLatitude = varLatitude * (Math.PI / 180);
                varLon = varLon * (Math.PI / 180);
                varLat = varLat * (Math.PI / 180);
                // 1st  X/Y Axis
                x0 = varLongitude * varRadius * Math.cos(varLatitude);
                y0 = varLatitude * varRadius;
                // 2nd X/Y Axis
                x1 = varLon * varRadius * Math.cos(varLat);
                y1 = varLat * varRadius;
                // Calculate Values
                dx = x0 - x1;
                dy = y0 - y1;
                // Determine Distance
                d = Math.sqrt((dx * dx) + (dy * dy));
                // Function Return
                return Math.round(d * 1000);
            };

Current Results:

Residence: 0m
Tron Utah: 532559m
Tron Enterprises: 45358m

Desired Results:

Residence: 0m
Tron Enterprises: 45358m
Tron Utah: 532559m

The "Sort by Distance" portion of the code is commented out because it doesn't work. Any assistance to correct this code or provide an alternative method is appreciated. I am a self taught amateur web developer.

Thanks,

3
  • What does the calculateDistance function do and return ? Commented Aug 18, 2014 at 14:49
  • Have have added that portion of the code to the question. :) Commented Aug 18, 2014 at 14:56
  • 1
    Try it like this -> jsfiddle.net/adeneo/nkLtj84y/1 Commented Aug 18, 2014 at 15:13

1 Answer 1

3
  1. first insert all your distance values into your data array. so you have the data like this:

        {
            "locationID": "9",
            "locationName": "Employee Residence",
            "locationLatitude": "34.47189",
            "locationLongitude": "-111.9896046999",
            "distance": 45456
        }
    

    this is done by iterating over the given data like this:

    for ( var i = 0; i < data.length; i++ ) {
        var entry = data[i];
        entry.distance = calculateDistance(entry.locationLongitude, entry.locationLatitude, LOCAL_LON, LOCAL_LAT);
    }
    
  2. sort your data by the distance property.

    var sortedData = data.sort(function(a, b) {
        return a.distance - b.distance;
    });
    

    you will now have an array sorted by distance

  3. iterate through the sorted array and create your html representation

Sign up to request clarification or add additional context in comments.

3 Comments

The distance is calculated based on the locations lat/lon which is produced from the ajax call. How to sort after this is obtained is where I am lost.
do you have the data prepared like in step 1?
The distance will be a dynamic value based on the users current location. The only data available is what is shown in the array portion of the question.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.