Costin
Costin

Reputation: 224

Add markers on Map using coordinates from database, retrieving data with JSON

I am trying to develop an app that onMapReady, adds markers that have coordinates retrieved from a database. Until now, for sending data to database(registration/login/get profile) etc., I have used JSON. Now I am trying the same way to get the latitude and longitude from the database, but the debugger showed me the variables are Null, after calling the Json method. Also, I would like to ask for some guindance of how should I place the markers? I mean, getting the coordinates with JSONObject, will it give me all the rows from the table? Or do I have to use other method to get all the rows and add marker for every one? Thanks!

AddMarker called right at the end of onMapReady to get the coordinates so i can add a marker:

 private void AdaugaMarker() {

    class AdaugaMarker extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... voids) {
            //creating request handler object
            RequestHandler requestHandler = new RequestHandler();

            //creating request parameters
            HashMap<String, String> params = new HashMap<>();
            params.put("problema", finalProblema);

            //returing the response
            return requestHandler.sendPostRequest(URLs.URL_GETALERTE, params);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            //displaying the progress bar while user registers on the server
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            //hiding the progressbar after completion

            try {
                //converting response to json object
                JSONObject obj = new JSONObject(s);

                //if no error in response
                if (!obj.getBoolean("error")) {
                    Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();

                    //getting the user from the response
                    JSONObject userJson = obj.getJSONObject("locatie");

                    latitudine_sql =Double.valueOf(userJson.getString("latitudine"));
                    longitudine_sql = Double.valueOf(userJson.getString("longitudine"));
                    tip_problema_sql = userJson.getString("tip_problema");
                } else {
                    Toast.makeText(getApplicationContext(), "Some error occurred", Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    //executing the async task
    AdaugaMarker ru = new AdaugaMarker();
    ru.execute();
}

.php called by URL_GETALERTE :

case 'getAlerte':

            if(isTheseParametersAvailable(array('problema'))){

                $problema = $_POST['problema'];

                $stmt = $conn->prepare("SELECT latitudine, longitudine, tip_problema FROM alerte WHERE tip_problema = ?");
                $stmt->bind_param("s", $problema);
                $stmt->execute();
                $stmt->store_result(); 
                if($stmt->num_rows > 0){
                $stmt->bind_result($latitudine, $longitudine, $problema);
                        $stmt->fetch();

                        $locatie = array(
                            'latitudine'=>$latitudine,
                            'longitudine'=>$longitudine,
                            'tip_problema'=>$problema

                        );
                    $response['error'] = false; 
                    $response['message'] = 'Alerta raportata';
                    $response['locatie'] = $locatie;    
                }else   {
                    $response['error'] = true; 
                    $response['message'] = 'Eroare de identificare a alertelor';
                }               
                }else{
                    $response['error'] = false; 
                    $response['message'] = 'Alerta nu a putut fi raportata';
                }
            break;

At the beginning of the .php I have added $response = array();

EDIT: Added JSONArray:

//converting response to json object
                JSONObject obj = new JSONObject(s);

                //if no error in response
                if (!obj.getBoolean("error")) {
                    Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();

                    JSONArray locatieArray = obj.getJSONArray("locatie");
                    for (int i = 0; i < locatieArray.length(); i++) {
                        JSONObject locatie = locatieArray.getJSONObject(i);
                        // check latitudine and longitudine is not null and if not null then cast these values and call the addMarker() method.
                        if(!locatie.isNull("latitudine") && !locatie.isNull("longitudine")) {
                            latitudine_sql =Double.valueOf(locatie.getString("latitudine"));
                            longitudine_sql = Double.valueOf(locatie.getString("longitudine"));
                            addMarker(latitudine_sql, longitudine_sql); // this method is implemented below
                        }
                        tip_problema_sql = locatie.getString("tip_problema");
                    }

                } else {
                    Toast.makeText(getApplicationContext(), "Some error occurred", Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

Upvotes: 0

Views: 93

Answers (2)

Jakir Hossain
Jakir Hossain

Reputation: 3930

Try this way

//if no error in response
if (!obj.getBoolean("error")) {
    Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();

    //getting the user from the response
    JSONObject userJson = obj.getJSONObject("locatie");

    // check latitudine and longitudine is not null and if not null then cast these values and call the addMarker() method. 
    if(!userJson.isNull("latitudine") && !userJson.isNull("longitudine")) {
        latitudine_sql =Double.valueOf(userJson.getString("latitudine"));
        longitudine_sql = Double.valueOf(userJson.getString("longitudine"));

        addMarker(latitudine_sql, longitudine_sql); // this method is implemented below
    }
    tip_problema_sql = userJson.getString("tip_problema");

} else {
    Toast.makeText(getApplicationContext(), "Some error occurred", Toast.LENGTH_SHORT).show();
}
private void addMarker(double latitude, double longitude){
   LatLng position = new LatLng(latitude, longitude);

   // Instantiating MarkerOptions class
   MarkerOptions options = new MarkerOptions();

   // Setting position for the MarkerOptions
   options.position(position);

   // Setting title for the MarkerOptions
   options.title("Position");

   // Setting snippet for the MarkerOptions
   options.snippet("Latitude:"+latitude+",Longitude:"+longitude);

   // Adding Marker on the Google Map
   googleMap.addMarker(options); // make sure you have initialized googleMap

   // Creating CameraUpdate object for position
   CameraUpdate updatePosition = CameraUpdateFactory.newLatLng(position);

   // Creating CameraUpdate object for zoom
   CameraUpdate updateZoom = CameraUpdateFactory.zoomBy(4);

   // Updating the camera position to the user input latitude and longitude
   googleMap.moveCamera(updatePosition);

   // Applying zoom to the marker position
   googleMap.animateCamera(updateZoom);
}

Update:

For multiple markers

// get locatie as JsonArray
JSONArray locatieArray = obj.getJSONArray("locatie");
for (int i = 0; i < locatieArray.length(); i++) {
      JSONObject locatie = locatieArray.getJSONObject[i];

      // check latitudine and longitudine is not null and if not null then cast these values and call the addMarker() method. 
      if(!locatie.isNull("latitudine") && !locatie.isNull("longitudine")) {
          latitudine_sql =Double.valueOf(userJson.getString("latitudine"));
          longitudine_sql = Double.valueOf(userJson.getString("longitudine"));

          addMarker(latitudine_sql, longitudine_sql); // this method is implemented below
      }
      tip_problema_sql = userJson.getString("tip_problema");
}

Upvotes: 1

jarvis
jarvis

Reputation: 61

You are receiving JSONArray of latitudine and longitudine but you are parsing as JSONObject. //Create this class first

public class Locatie {
private Double latitudine;

private String tip_problema;

private Double longitudine;

public Double getLatitudine() {
    return latitudine;
}

public void setLatitudine(Double latitudine) {
    this.latitudine = latitudine;
}

public String getTip_problema() {
    return tip_problema;
}

public void setTip_problema(String tip_problema) {
    this.tip_problema = tip_problema;
}

public Double getLongitudine() {
    return longitudine;
}

public void setLongitudine(Double longitudine) {
    this.longitudine = longitudine;
}

@Override
public String toString() {
    return "ClassPojo [latitudine = " + latitudine + ", tip_problema = " + tip_problema + ", longitudine = " + longitudine + "]";
}

}

 if (!obj.getBoolean("error")) {
            ArrayList<Locatie> locatieList = new ArrayList<>();
            Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();

            //getting the user from the response
            JSONArray userLatLngArray = obj.getJSONArray("locatie");
            for (int i = 0; i < userLatLngArray.length(); i++) {
                Locatie locate = new Locatie();
                JSONObject data = userLatLngArray.getJSONObject[i];


                //Here you need to create List of POJO class to save all lat log values in list so //you can access any where.
                locate.setLatitudine(Double.valueOf(data.getString("latitudine")));
                locate.longitudine_sql(Double.valueOf(data.getString("longitudine")));
                locate.setLatitudine(data.getString("tip_problema"));

                locatieList.add(locate);

                //locatieList will be arraylist of lat lng pojo

            }

        } else {
            Toast.makeText(getApplicationContext(), "Some error occurred", Toast.LENGTH_SHORT).show();
        }

Upvotes: 1

Related Questions