Skip to content
Advertisement

Adding multiple markers to google maps API from volley repose in android Java

I am new to Google Maps API for android but I would like to create a view in my android app to show the locations of some providers form the database. So far I have done the following:

      public void onResponse(String response) {
            Log.d(TAG, "Response: " + response);
            try {
                JSONObject jsonObject;
                JSONObject drinkObject = new JSONObject(response);
                JSONArray jsonArray = drinkObject.getJSONArray("vendors");
                for(int i=0; i<jsonArray.length();i++){
                    jsonObject = jsonArray.getJSONObject(i);
                    latlngs.add(new LatLng(jsonObject.getDouble("latitude"), jsonObject.getDouble("longitude")));
                }
                for (LatLng point : latlngs) {
                    options.position(point);
                    options.title("mama fua service provider");
                    options.snippet("someDesc");
                    googleMap.addMarker(options);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

With this I have been able to add the markers but they are all grouped together into a whole page map of the world as seen here output This means that for a user to view the other makers he has to manually zoom in. How can I achieve this? what changes do I have to make to my code or can someone point me to the right direction? After following an answer on a similar question as suggested by @Andy, I have updated my code to

public void onMapReady(GoogleMap googleMap) {

    final String TAG = ItemisedMapsActivity.class.getSimpleName();

    StringRequest strReq = new StringRequest(Request.Method.POST, Link.URL_PROVIDER, response -> {
        Log.d(TAG, "Response: " + response);
        try {
            JSONObject jsonObject;
            JSONObject drinkObject = new JSONObject(response);
            JSONArray jsonArray = drinkObject.getJSONArray("vendors");
            for(int i=0; i<jsonArray.length();i++){
                jsonObject = jsonArray.getJSONObject(i);
                LatLng vnr = new LatLng(jsonObject.getDouble("latitude"), jsonObject.getDouble("longitude"));
                MarkerOptions vnrMarker = new MarkerOptions();
                vnrMarker.position(vnr);
                vnrMarker.title(jsonObject.getString("name"));
                vnrMarker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
                markerList.add(vnrMarker);
            }
            showAllMarkers(googleMap);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }, error -> {
        Log.e(TAG, "Request Error: " + error.getMessage());
        Toast.makeText(this, " An error has occurred "+error.getMessage(), Toast.LENGTH_LONG).show();
    }) {
        @Override
        protected Map<String, String> getParams() {
            // Posting params to register url
            Map<String, String> params = new HashMap<>();
            params.put("town", town);
            return params;
        }
    };
    // Adding request to request queue
    RequestQueue providerRequestQue = Volley.newRequestQueue(this);
    providerRequestQue.add(strReq);
}

private void showAllMarkers(GoogleMap googleMap) {
    LatLngBounds.Builder builder = new LatLngBounds.Builder();
    for (MarkerOptions m : markerList) {
        builder.include(m.getPosition());
    }
    LatLngBounds bounds = builder.build();
    int width = getResources().getDisplayMetrics().widthPixels;
    int height = getResources().getDisplayMetrics().heightPixels;
    int padding = (int) (width * 0.30);
    // Zoom and animate the google map to show all markers
    CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding);
    googleMap.animateCamera(cu);
}

This does zoom in to what is actually the position of the markers except that the markers are not shown on the map new output

Advertisement

Answer

After numerous searches and following some of the helpful advise in the comments, I solved the problem and here is the code that worked just incase someone has the same problem in future. Once the map is ready, retrieve the serve information using volley, then iterate through the response array and add markers to the markersoption arraylist

public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    banPoint =BitmapDescriptorFactory.fromResource(R.drawable.pincode);

    final String TAG = ItemisedMapsActivity.class.getSimpleName();

    StringRequest strReq = new StringRequest(Request.Method.POST, Link.URL_PROVIDER, response -> {
        try {
            JSONObject jsonObject;
            JSONObject drinkObject = new JSONObject(response);
            JSONArray jsonArray = drinkObject.getJSONArray("vendors");
            for(int i=0; i<jsonArray.length();i++){
                jsonObject = jsonArray.getJSONObject(i);
                LatLng vnr = new      LatLng(jsonObject.getDouble("latitude"), jsonObject.getDouble("longitude"));
                MarkerOptions vnrMarker = new MarkerOptions();
                vnrMarker.position(vnr);
                vnrMarker.title(jsonObject.getString("name"));
                vnrMarker.snippet("Mama fua service provider");
                vnrMarker.icon(banPoint);
                markerList.add(vnrMarker);
            }
            showAllMarkers(mMap);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }, error -> {
        Log.e(TAG, "Request Error: " + error.getMessage());
        Toast.makeText(this, " An error has occurred "+error.getMessage(), Toast.LENGTH_LONG).show();
    }) {
        @Override
        protected Map<String, String> getParams() {
            // Posting params to register url
            Map<String, String> params = new HashMap<>();
            params.put("town", town);
            return params;
        }
    };
    // Adding request to request queue
    RequestQueue providerRequestQue = Volley.newRequestQueue(this);
    providerRequestQue.add(strReq);
}

Then create a method to use to calculate the position of all the markers and zoom to their points showing all of them in the map

      private void showAllMarkers(GoogleMap mMap) {
    LatLngBounds.Builder builder = new LatLngBounds.Builder();
    for (MarkerOptions m : markerList) {
        builder.include(m.getPosition());
        // add the parkers to the map
        mMap.addMarker(m);
    }
    LatLngBounds bounds = builder.build();
    int width = getResources().getDisplayMetrics().widthPixels;
    int height = getResources().getDisplayMetrics().heightPixels;
    int padding = (int) (width * 0.30);
    // Zoom and animate the google map to show all markers
    CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding);
    mMap.animateCamera(cu);
}
10 People found this is helpful
Advertisement