java - 如何显示距离用户位置最近的标记?
问题描述
我有一个方法“onPostExecute()”,它显示从 JSON 解析的标记,它工作正常。现在我想显示离我当前位置最近的标记。我该怎么办?
这是下面的代码。
public void onPostExecute(String json) {
try {
// De-serialize the JSON string into an array of branch objects
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
LatLng latLng = new LatLng(jsonObj.getDouble("latitude"),
jsonObj.getDouble("longitude"));
// Create a marker for each branch in the JSON data.
map.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))
.title(jsonObj.getString("name"))
// .snippet(Integer.toString(jsonObj.getInt("snippet")))
.snippet(jsonObj.getString("snippet"))
.position(latLng));
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Error processing JSON", e);
}
}
解决方案
您应该阅读本指南Android Location Strategies。您需要跟踪用户位置,当您获得它时,您可以将您的每个JSON
标记与它进行比较。尝试这样的事情:
public void onPostExecute(String json) {
Location closestMark;
try {
// De-serialize the JSON string into an array of branch objects
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
LatLng latLng = new LatLng(jsonObj.getDouble("latitude"),
jsonObj.getDouble("longitude"));
Location currentMark = new Location("");
currentMark.setLatitude(latLng.latitude);
currentMark.setLongitude(latLng.longitude);
if (closestMark == null || (userLocation.distanceTo(currentMark)
< userLocation.distanceTo(closestMark))
{
closestMark = currentMark;
}
// Create a marker for each branch in the JSON data.
map.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))
.title(jsonObj.getString("name"))
// .snippet(Integer.toString(jsonObj.getInt("snippet")))
.snippet(jsonObj.getString("snippet"))
.position(latLng));
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Error processing JSON", e);
}
}
希望这可以帮助。
推荐阅读
- python - 如何将其转换为列表理解
- ssis - ETL包配置问题:如何设置GeneratedFromPackageID?
- performance-testing - k6:WARpanic:运行时错误:无效的内存地址或 nil 指针取消引用
- java - 将外部 JAR 添加到 Grails 4.0 应用程序
- python - 在 Python 中,如何解决不同维度矩阵的广义特征值问题?
- ios - 构建 iOS 应用程序以在颤振上发布的问题
- arduino - Marlin 2.0.5 编译错误 collect2.exe
- javascript - 如何获取元素嵌套项
- mysql - 为什么在尝试将 if 语句放入触发器时会出现语法错误?
- python - 模式名称可变时 Django 模板中的 URL 反转