【发布时间】:2017-12-31 08:26:15
【问题描述】:
编辑: 建议我使用this 公式来计算我当前位置与放置的标记之间的距离,但无论我将标记,即1.004822115417686E7。我将在我更新的代码中展示该方法。
我只想要从我的位置到放置的标记的距离。我尝试使用 distanceTo(Location dest) 方法,但我不知道如何将我的 Marker LatLng 转换为 Location 对象,如果可能的话。结果,我决定使用Location.distanceBetween 方法。
问题是我的结果根本不正确。我究竟做错了什么?我是否误读了 Android 文档?
我所做的只是执行onMapLongClick 来添加标记。当前位置没有标记。它只是显示用户所在位置的蓝点。
地图使用基础:
用户停车。用户在他们停放的地图上放置标记。用户去附近的建筑物做某事。用户回来,打开应用程序,找到汽车。应用程序将显示到汽车的距离。距离不需要考虑障碍物、转弯等。直线距离就可以了。
代码:
@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,它说:
计算出的距离存储在结果[0]中
我实际上是在离我的位置 20-30 英尺的地方放置一个标记,那么这个奇怪的输出是什么?我尝试的新功能甚至都不正确。
【问题讨论】:
-
这不是我在 Android 谷歌地图上计算距离的方式。我只使用了两组纬度/经度值以及 Haversine 公式。
-
我也试过了。我仍然得到同样奇怪的输出。
标签: android google-maps google-maps-markers