编辑:有人建议我使用 this公式来计算我当前位置和放置的标记之间的距离,但无论我将标记放置在何处,我都会得到相同的结果,即 1.004822115417686E7
。我将在更新的代码中展示该方法。
我只想要从我的位置到放置的标记的距离。我尝试使用 distanceTo(Location dest)
方法,但我不知道如何将 Marker LatLng 转换为 Location 对象,如果可能的话。因此,我决定使用 Location.distanceBetween
方法。
问题是我的结果根本不正确。我究竟做错了什么?我是否误读了 Android 文档?
我所做的只是执行 onMapLongClick
来添加标记。当前位置上没有标记。它将只是显示用户所在位置的蓝点。
map 使用基础:
用户 parking 。用户在他们停放的 map 上放置标记。用户去附近的建筑物做某事。用户回来,打开应用程序,找到汽车。应用程序将显示到汽车的距离。距离不需要考虑障碍物、转弯等。直线距离即可。
代码:
@Override
public void onMapLongClick(LatLng latLng) {
mMap.clear();
//m is the Marker
m = mMap.addMarker(new MarkerOptions()
.position(latLng)
.title("My Ride")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.custom_marker30x48)));
float[] results = new float[1];
Location currentPos = new Location(LocationManager.GPS_PROVIDER);
latLng = m.getPosition();
Location.distanceBetween(currentPos.getLatitude(), currentPos.getLongitude(), latLng.latitude, latLng.longitude, results);
Log.d(TAG, "Distance using distanceBetween(): " + results[0] + " meters");
Log.d(TAG, "Distance using meterDistanceBetweenPoints: " + meterDistanceBetweenPoints((float)currentPos.getLatitude(), (float)currentPos.getLongitude(), (float)latLng.latitude, (float)latLng.longitude));
Toast.makeText(getApplicationContext(), "Marker Added", Toast.LENGTH_SHORT).show();
}
private double meterDistanceBetweenPoints(float lat_a, float lng_a, float lat_b, float lng_b) {
float pk = (float) (180.f/Math.PI);
float a1 = lat_a / pk;
float a2 = lng_a / pk;
float b1 = lat_b / pk;
float b2 = lng_b / pk;
double t1 = Math.cos(a1) * Math.cos(a2) * Math.cos(b1) * Math.cos(b2);
double t2 = Math.cos(a1) * Math.sin(a2) * Math.cos(b1) * Math.sin(b2);
double t3 = Math.sin(a1) * Math.sin(b1);
double tt = Math.acos(t1 + t2 + t3);
return 6366000 * tt;
}
这是 Logcat 中的输出:
Distance using distanceBetween(): 1.0061643E7 meters
Distance using meterDistanceBetweenPoints: 1.004822115417686E7
我在这里做错了什么?根据Android Docs ,它说:
The computed distance is stored in results[0]
我实际上是在距离我的位置 20-30 英尺处放置了一个标记,那么这个奇怪的输出是什么?对于我尝试的新功能,它甚至都不正确。
最佳答案
在 onMapLongClick 中,您将通过此行清除所有先前的标记:
mMap.clear();
因此每次放置新标记时,以前的标记都会被清除。如果你想在两个地方都有标记,即你的位置和点击的位置,那么每次在 onMapLongClick 上做:
@Override
public void onMapLongClick(LatLng latLng) {
mMap.clear();
//marker at clicked location
mMap.addMarker(new MarkerOptions()
.position(latLng)
.title("My Ride")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.custom_marker30x48)));
//marker at your location
mMap.addMarker(new MarkerOptions()
.position(MyLatLng)
.title("My Location")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.custom_marker30x48)));
//----
//do whatever else you want
//----
}
和 MyLatLng
你可以从 onLocationChanged
函数得到:
Location MyLatLng;
@Override
public void onLocationChanged(Location location) {
MyLatLng = location;
}
要计算两个位置之间的距离,请引用此解决方案: https://stackoverflow.com/a/8050255/7026525
关于android - 如何显示 Location.distanceBetween 的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48041057/