首页 > 解决方案 > 如何显示距离用户位置最近的标记?

问题描述

我有一个方法“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);
        }

    }

标签: javaandroid

解决方案


您应该阅读本指南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);
    }

}

希望这可以帮助。


推荐阅读