Steven Hammons
Steven Hammons

Reputation: 118

How to find nearest marker on Google Maps Activity in Android using JSON Data?

I'm using this example to show markers on a Google Maps Activity. Example: https://gist.github.com/TimPim/5902100

void createMarkersFromJson(String json) throws JSONException {
    // De-serialize the JSON string into an array of city objects
    JSONArray jsonArray = new JSONArray(json);
    for (int i = 0; i < jsonArray.length(); i++) {
        // Create a marker for each city in the JSON data.
        JSONObject jsonObj = jsonArray.getJSONObject(i);
        map.addMarker(new MarkerOptions()
            .title(jsonObj.getString("name"))
            .snippet(Integer.toString(jsonObj.getInt("population")))
            .position(new LatLng(
                    jsonObj.getJSONArray("latlng").getDouble(0),
                    jsonObj.getJSONArray("latlng").getDouble(1)
             ))
        );
    }
}

I would like to reuse this code below to check the closest marker for the JSON information to find the closest marker. Code below from Display title of closest marker from my current position Google Maps v2

List<MyMarkerObj> m = data.getMyMarkers();
float mindist;
int pos=0;
            for (int i = 0; i < m.size(); i++) {
                String[] slatlng =  m.get(i).getPosition().split(" ");
                LatLng lat = new LatLng(Double.valueOf(slatlng[0]), Double.valueOf(slatlng[1]));
                map.addMarker(new MarkerOptions()
                        .title(m.get(i).getTitle())
                        .snippet(m.get(i).getSnippet())
                        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
                        .position(lat)
                        );

                float[] distance = new float[1];
                Location.distanceBetween(currentlat, currentlong,Double.valueOf(slatlng[0]), Double.valueOf(slatlng[1]), distance);
                if(i==0) mindist=distance[0];
                else if(mindist>distance[0]) {
                   mindist=distance[0];
                   pos=i;
                 }
            }
  Toast.makeText(getActivity(), "Closest Marker Distance: "+ m.get(pos).getTitle() +" "+mindist, Toast.LENGTH_LONG).show();

Upvotes: 1

Views: 1384

Answers (1)

Daniel Nugent
Daniel Nugent

Reputation: 43322

You don't need the m array for your case, as you already have your data in a JSONArray.

Simply iterate through the JSONArray, keep track of the current-nearest Marker, and when the loop is done you'll have a reference to the nearest Marker.

Combining your code with the relevant parts of the other answer:

Marker mClosestMarker;
float mindist;
void createMarkersFromJson(String json) throws JSONException {
    // De-serialize the JSON string into an array of city objects
    JSONArray jsonArray = new JSONArray(json);
    for (int i = 0; i < jsonArray.length(); i++) {
        // Create a marker for each city in the JSON data.
        JSONObject jsonObj = jsonArray.getJSONObject(i);
        double lat = jsonObj.getJSONArray("latlng").getDouble(0);
        double lon = jsonObj.getJSONArray("latlng").getDouble(1);
        Marker currentMarker = map.addMarker(new MarkerOptions()
            .title(jsonObj.getString("name"))
            .snippet(Integer.toString(jsonObj.getInt("population")))
            .position(new LatLng(
                    lat,
                    lon
             ))
        );

      float[] distance = new float[1];
      Location.distanceBetween(currentlat, currentlong, lat, lon, distance);
      if(i==0) {
        mindist = distance[0];
      } else if (mindist > distance[0]) {
        mindist=distance[0];
        mClosestMarker = currentMarker;
      }
    }

    Toast.makeText(MainActivity.this, "Closest Marker Distance: "+ mClosestMarker.getTitle() + " " + mindist, Toast.LENGTH_LONG).show();
}

Note If you need help getting the current location for currentlat and currentlong, see here: How can I show current location on a Google Map on Android Marshmallow?

If you follow the answer there in order to get the current location, and you have placed a "current location" Marker, you can simply do this:

LatLng currentLatLng = mCurrLocationMarker.getPosition();
Location.distanceBetween(currentLatLng.latitude, currentLatLng.longitude, lat, lon, distance);

Upvotes: 2

Related Questions