0

I have a method "onPostExecute()" that shows Markers parsed from JSON and it worked fine. Now I want to show the nearest Marker from my current position. What should I do?

Here is the code below.

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);
        }

    }
  • Go through the list of markers. For each one calculate the distance between the marker and the user. Then determine the closest one – vincrichaud Apr 26 '18 at 15:23
  • @vincrichaud Thank you for the help. But how am I going to do that? –  Apr 26 '18 at 15:29
  • [do a for loop](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html) and [calculate distance](https://stackoverflow.com/questions/8049612/calculating-distance-between-two-geographic-locations). It took me 5 minutes of research. This is something you could have done by yourself – vincrichaud Apr 26 '18 at 15:51

2 Answers2

0

You should read this guide Android Location Strategies. You need to track the user location, when you get it you can get you can compare each of your JSON mark with it. Try something like this:

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);
    }

}

Hope this helps.

Jagrut Sharma
  • 4,574
  • 3
  • 14
  • 19
Robert LaFondue
  • 191
  • 1
  • 9
0

Here is how I solved my problem. It might help somebody else too.

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"));

                    float[] distance = new float[1];
                    LatLng currentLatLng = mCurrLocationMarker.getPosition();

                    //move CameraPosition on user Location
                    if (i == 0) {
                        CameraPosition cameraPosition = new CameraPosition.Builder()
                                .target(currentLatLng).zoom(13).build();

                        map.animateCamera(CameraUpdateFactory
                                .newCameraPosition(cameraPosition));
                    }

                    // Create a marker for each branch in the JSON data.
                    Marker currentMarker = map.addMarker(new MarkerOptions()
                            .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))
                            .title(jsonObj.getString("name"))
                            .snippet(jsonObj.getString("snippet"))
                            .position(latLng)
                            .visible(false)
                    );

                    Location.distanceBetween(currentLatLng.latitude, currentLatLng.longitude, latLng.latitude, latLng.longitude, distance);

                    if (i == 0) {
                        minDist = distance[0];
                    } else if (minDist > distance[0]) {
                        minDist = distance[0];
                        mClosestMarker = currentMarker;
                    }
                }
                Toast.makeText(NearestBranch.this, "Nearest Branch Distance: "+ mClosestMarker.getTitle() + " " + minDist, Toast.LENGTH_LONG).show();
                map.addMarker(new MarkerOptions()
                        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))
                        .title(mClosestMarker.getTitle())
                        .snippet(mClosestMarker.getSnippet())
                        .position(mClosestMarker.getPosition())
                );

            }
            catch (JSONException e) {
                Log.e(LOG_TAG, "Error processing JSON", e);
            }
    }