我从我的数据库中获取包含TITLE,SNIPPET和LOCATION的数据,并尝试测试以检查我当前位置之间的距离。我很困惑如何显示最接近我位置的标记的标题。
List<MyMarkerObj> m = data.getMyMarkers();
for (int i = 0; i < m.size(); i++) {
String[] slatlng = m.get(i).getPosition().split(" ");
LatLng lat = new LatLng(Double.valueOf(slatlng[0]), Double.valueOf(slatlng[1]));
map.addMarker(new MarkerOptions()
.title(m.get(i).getTitle())
.snippet(m.get(i).getSnippet())
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.position(lat)
);
float[] distance = new float[1];
Location.distanceBetween(currentlat, currentlong,Double.valueOf(slatlng[0]), Double.valueOf(slatlng[1]), distance);
Toast.makeText(getActivity(), "Marker Distance: "+ m.get(i).getTitle() +" "+distance[0], Toast.LENGTH_LONG).show();
}
答案 0 :(得分:5)
我在这里做了一些改变。试试吧..
List<MyMarkerObj> m = data.getMyMarkers();
float mindist;
int pos=0;
for (int i = 0; i < m.size(); i++) {
String[] slatlng = m.get(i).getPosition().split(" ");
LatLng lat = new LatLng(Double.valueOf(slatlng[0]), Double.valueOf(slatlng[1]));
map.addMarker(new MarkerOptions()
.title(m.get(i).getTitle())
.snippet(m.get(i).getSnippet())
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.position(lat)
);
float[] distance = new float[1];
Location.distanceBetween(currentlat, currentlong,Double.valueOf(slatlng[0]), Double.valueOf(slatlng[1]), distance);
if(i==0) mindist=distance[0];
else if(mindist>distance[0]) {
mindist=distance[0];
pos=i;
}
}
Toast.makeText(getActivity(), "Closest Marker Distance: "+ m.get(pos).getTitle() +" "+mindist, Toast.LENGTH_LONG).show();
答案 1 :(得分:2)
您可以使用此简单函数计算纬度和经度格式中两点之间的距离,它就像一个魅力,然后您可以检查距您所在位置最近的距离。只需传递两个位置的纬度和经度
public double distanceFrom(double lat1, double lng1, double lat2, double lng2) {
double earthRadius = 3958.75;
double dLat = Math.toRadians(lat2-lat1);
double dLng = Math.toRadians(lng2-lng1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.sin(dLng/2) * Math.sin(dLng/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double dist = earthRadius * c;
int meterConversion = 1609;
return new Double(dist * meterConversion).floatValue(); // this will return distance
}