斗士狗 2014-08-18 14:42 采纳率: 0%
浏览 13

排序数组结果

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,

  • 写回答

1条回答 默认 最新

  • weixin_33735077 2014-08-18 14:50
    关注
    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

    评论

报告相同问题?

悬赏问题

  • ¥25 关于##爬虫##的问题,如何解决?:
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误