我正在制作一个 android 应用程序,它将列出不在 google 位置上的特定位置。我有所有的经纬度和地名,它们不会改变。我可以在我的自定义列表中显示它们,它工作正常问题是我想按与您(用户)位置的距离对它们进行排序并显示它们旁边的距离。
我尝试了很多不同的方法,但有点卡住了。我想说我是编程新手,并且在这个应用程序中遇到了挫折,如果有人能提供帮助,我将不胜感激。
所以我要问的问题是我如何/应该如何按距离对位置进行排序,以便将它们添加到我的自定义列表中。
// create array to hold place names to be looped through later
String[] placenames = { "place1", "place2",
"place3", "place4" };
// // create arrays to hold all the latitudes and longitudes
double[] latArray = new double[] { 51.39649, 51.659775, 51.585433,
51.659775 };
double[] lngArray = new double[] { 0.836523, 0.539901, 0.555385,
0.539901, };
// hard code my location for test purposes only
Location MyLocation = new Location("My location");
MyLocation.setLatitude(51.659775);
MyLocation.setLongitude(0.539901);
for (int i = 0; i < placenames.length;) {
// Place location object
Location PlaceName = new Location(placenames[i]);
PlaceName.setLatitude(latArray[i]);
PlaceName.setLongitude(lngArray[i]);
i++;
// calculate distance in meters
float distanceInMeters = PlaceName.distanceTo(MyLocation);
// convert to double
double DistanceInMiles = distanceInMeters * 0.000621371;
dimint = (int) DistanceInMiles;
// format numbers to two decimal places
DecimalFormat df = new DecimalFormat("#.##");
dim = df.format(DistanceInMiles);
//make treemap and then sortedmap to sort places by distance
TreeMap<Integer, String> treemap = new TreeMap<Integer, String>();
SortedMap<Integer, String> treemapsorted = new TreeMap<Integer,String>();
treemap.put(dimint, PlaceName.getProvider());
treemapsorted = treemap.subMap(0, 5);
// Toast for test purpose to see if sort is working
Toast tst = Toast.makeText(this, treemapsorted.entrySet()
.toString(), Toast.LENGTH_SHORT);
tst.show();
CustomList place_data[] = new CustomList[] {
// This is the problem part
new CustomList(R.drawable.picture1, treemapsorted.get(dimint)),
};
CustomListAdapter adapter = new CustomListAdapter(this,
R.layout.listview_item_row, place_data);
listView1 = (ListView) findViewById(R.id.listView1);
listView1.setAdapter(adapter);
;
}