Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Google Map showing only one marker

    • 1
    • 0
    • 0
    • 3
    • 0
    • 0
    • 0
    • 1.59k
    Answer it

    Hi,

    I am using Google Map in my app. I have added treeid, and its lat and lng location. I want to retreive these location and show in google marker using volley library.

    But I am able to get only one marker location.Please help me where I am getting wrong in my code?

    My database server link: http://plantnow.net16.net/googlemaplocations.php

    I am getting only treeid = 2

    My Map activity:

    btMap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
    
                String search = String.valueOf(inputSearch.getSelectedItem()).toString();
    
                mMap = mMapView.getMap();
    
                mMap.clear();
    
                //getSelectedLocations(search);
    
                Toast.makeText(getActivity().getApplicationContext(), "Locations of " + search + " trees", Toast.LENGTH_LONG).show();
    
    
                if (search.equals("All Locations")) {
                    double latitude = 0;
                    double longitude = 0;
                    String mark;
    
                    getLocations();
    
                    Toast.makeText(getActivity().getApplicationContext(), "All trees locations ", Toast.LENGTH_LONG).show();
    
    
    
                } else {
    
                    Toast.makeText(getActivity().getApplicationContext(), "Location are not available ", Toast.LENGTH_LONG).show();
                }
    
            }
        });
    
        return v;
    }
    
    
         private void getLocations() {
        // Tag used to cancel the request
        String tag_string_req = "req_location";
    
       // pDialog.setMessage("Logging in ...");
       // showDialog();
    
        StringRequest strReq = new StringRequest(Request.Method.POST,
                AppConfig.URL&#95;MAPLOCATION, new Response.Listener<String>() {
    
            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Location Response: " + response.toString());
                hideDialog();
    
                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");
                    List<Marker> markers = new ArrayList<Marker>();
    
                    // Check for error node in json
                    if (!error) {
    
                        JSONObject location = jObj.getJSONObject("tree");
    
                        for (int i = 0; i < location.length(); i++) {
    
                            String treeid = location.getString("treeid");
                            String treespecies = location.getString("treespecies");
                            Double treelatitude = location.getDouble("treelatitude");
                            Double treelongitude = location.getDouble("treelongitude");
    
                            LatLng latlng = new LatLng(treelatitude, treelongitude);
    
                            Marker marker =  mMap.addMarker(new MarkerOptions().title(treeid)
                                            .position(new LatLng(treelatitude, treelongitude))
                            );
                               markers.add(marker);
                            // Moving CameraPosition to last clicked position
                            mMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
    
                            // Setting the zoom level in the map on last position is clicked
                            mMap.animateCamera(CameraUpdateFactory.newLatLng(latlng));
    
                            mMap.animateCamera(CameraUpdateFactory.zoomTo(2));
    
                        }
    
                        // Launch main activity
    
                    } else {
                        // Error in login. Get the error message
                        String errorMsg = jObj.getString("error&#95;msg");
                        Toast.makeText(getActivity().getApplicationContext(),
                                errorMsg, Toast.LENGTH&#95;LONG).show();
                    }
                } catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                    Toast.makeText(getActivity().getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH&#95;LONG).show();
                }
    
            }
        }, new Response.ErrorListener() {
    
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Login Error: " + error.getMessage());
                Toast.makeText(getActivity().getApplicationContext(),
                        error.getMessage(), Toast.LENGTH&#95;LONG).show();
                hideDialog();
            }
        }) {
    
    
    
        };
    
        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag&#95;string&#95;req);
    }
    

    My PHP Code:

         <?php
    
           define('&#95;&#95;ROOT&#95;&#95;', dirname(dirname(&#95;&#95;FILE&#95;&#95;))); 
       require&#95;once(&#95;&#95;ROOT&#95;&#95;.'/public&#95;html/Config.php');
    
    
     // Connecting to mysql database
        $mysqli = new mysqli(DB&#95;HOST, DB&#95;USER, DB&#95;PASSWORD, DB&#95;DATABASE);
    
           // json response array
              $response = array("error" => FALSE);
    
    
    
    
    // get the tree details for google map marker
        if($stmt = $mysqli->query("SELECT * FROM tree where `treecondition` IN ( 'Balanced', 'Healthy', 'Imbalance', 'Dangerous', 'Transplanted', 'Dieseased')")){
    
    
    
     if ($stmt->num&#95;rows) {
    
    
           while($tree = $stmt->fetch&#95;assoc()) {
    
            $response["error"] = FALSE;
    
            $response ["tree"] ["treeid"] = $tree['treeid'];
            $response ["tree"] ["treespecies"] = $tree['treespecies'];
            $response ["tree"] ["treelatitude"] = $tree['treelatitude'];
            $response ["tree"] ["treelongitude"] = $tree['treelongitude'];
            echo json&#95;encode($response),'<br>';
         } 
         }else {
         // user is not found with the credentials
       $response["error"] = TRUE;
        $response["error&#95;msg"] = "Tree list view credentials are wrong. Please try again!";
       echo json&#95;encode($response);
       }
        $mysqli->close();
            }
    

 3 Answer(s)

  • Seems there is problem at parsing only first object is getting fetched from json array you are receiving so please use the following method for the parsing

        public void requestJSONArray(final RequestCallback callback) {
    
                JsonArrayRequest req = new JsonArrayRequest(map_url,
                        new Response.Listener() {
                            @Override
                            public void onResponse(JSONArray response) {
                                Log.d(TAG, response.toString());
    
                                    // Parsing json array response
                                    // loop through each json object
                                    List json_reponse = new ArrayList<>();
                                    json_reponse.clear();
                                    for (int i = 0; i < response.length(); i++) {
    
                                        try {
                                            JSONObject json_object = (JSONObject) response
                                                    .get(i);
                                            String treeid = json_object.getString("treeid");
                                            String treespecies = json_object.getString("treespecies");
                                            String treelatitude = json_object.getString("treelatitude");
                                            String treelongitude = json_object.getString("treelongitude");
    
                                            json_reponse.add(new MapModal(treeid,treespecies, treelatitude, treelongitude));
    
                                        }catch (Exception e){e.printStackTrace();}
    
                                    }
                                    Log.d(TAG, ""+json_reponse.size());
        //                            txtResponse.setText(jsonResponse);
    
    
        //                        hidepDialog();
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d(TAG, "Error: " + error.getMessage());
        //                Toast.makeText(getApplicationContext(),
        //                        error.getMessage(), Toast.LENGTH_SHORT).show();
        //                hidepDialog();
                    }
                });
    
                // Adding request to request queue
                AppInitializer.getContext().getVolleyRequestQueu().add(req);
            }
    
    

    and the modal class for the same is

    ** * Created by amitrai on 26/10/15. */

    public class MapModal {
    
        public MapModal(String treeid,String treespecies, String treelatitude,String treelongitude){
            this.treeid = treeid;
            this.treespecies = treespecies;
            this.treelatitude = treelatitude;
            this.treelongitude =treelongitude;
        }
    
        public String treeid,treespecies, treelatitude,treelongitude;
    
        public String getTreeid() {
            return treeid;
        }
    
        public void setTreeid(String treeid) {
            this.treeid = treeid;
        }
    
        public String getTreespecies() {
            return treespecies;
        }
    
        public void setTreespecies(String treespecies) {
            this.treespecies = treespecies;
        }
    
        public String getTreelatitude() {
            return treelatitude;
        }
    
        public void setTreelatitude(String treelatitude) {
            this.treelatitude = treelatitude;
        }
    
        public String getTreelongitude() {
            return treelongitude;
        }
    
        public void setTreelongitude(String treelongitude) {
            this.treelongitude = treelongitude;
        }
    
    }
    
    

    I have tested it all the objects are getting stored in list now just create a for loop till the size of list and do whatever you want with all the data fetched from json array.

    If answers is helpful please mark the answer correct ! Happy coding :)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: