我有一个应用程序,我使用纬度和经度显示最近的事件(地点)距离。用户纬度和经度是可变的,但事件纬度和经度是固定的。但是,我无法得到正确的距离是km。例如,谷歌地图的正确距离为6.7公里,但其显示为8663.90公里。我是android的新手所以无法得到解决方案。任何帮助都会很棒!!我的代码是
{ double doubleInstance = d.getDistance(Lat1, Lon1, d.getLatitude(), d.getLongitude(), "N");
String dInstance = String.format("%.2f",doubleInstance);
lblview1.setText(" " + String.valueOf(dInstance) + " Km"); }
和
{ public double getDistance(double lat1, double lon1, double lat2, double lon2, String unit) {
int Radius = 6371;// radius of earth in Km
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
+ Math.cos(Math.toRadians(lat1))
* Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 2)
* Math.sin(dLon / 2);
double c = 2 * Math.asin(Math.sqrt(a));
double valueResult = Radius * c;
double km = valueResult / 1;
DecimalFormat newFormat = new DecimalFormat("####");
int kmInDec = Integer.valueOf(newFormat.format(km));
double meter = valueResult % 1000;
int meterInDec = Integer.valueOf(newFormat.format(meter));
Log.i("Radius Value", "" + valueResult + " KM " + kmInDec
+ " Meter " + meterInDec);
return Radius * c;
} }
答案 0 :(得分:2)
设置您的活动地点。并使用位置管理器获取您当前的位置。
double latitude=lat;
double longitude=lng;
float distance=0;
Location crntLocation=new Location("crntlocation");
crntLocation.setLatitude(currentLatitude);
crntLocation.setLongitude(currentLongitude);
Location eventLocation=new Location("eventlocation");
eventLocation.setLatitude(latitude);
eventLocation.setLongitude(longitude);
//float distance = crntLocation.distanceTo(eventLocation); in meters
distance =crntLocation.distanceTo(eventLocation) / 1000; // in kms
答案 1 :(得分:1)
使用Location类方法获取两个坐标之间的距离,如;
Location.distanceBetween(obj.getLatitude(), obj.getLongitude(),
mapCircle.getCenter().latitude, mapCircle.getCenter().longitude, distance);