Android studio execute AsyncClass before onMapReady - android

I have this code where i have to call data from database yung asynctask the coordinates for my googlemap. but the onMapReady is executing before my Asynctask so the location is always null. I call the asynctask on my oncreate here is my code.
AsyncTask on onCreate
HashMap<String, String> postData = new HashMap<>();
postData.put("rqstID", rqstID);
AsyncClass taskDetails = new AsyncClass(AcceptActivity.this, postData, "Getting details", new AsyncResponse() {
#Override
public void processFinish(String s) {
Log.d("AcceptActivity", s);
JSONObject parentObject = null;
try {
parentObject = new JSONObject(s);
JSONArray parentArray = parentObject.getJSONArray("result");
JSONObject finalObject = parentArray.getJSONObject(0);
lat1 = finalObject.getString("rqstLat");
lng1 = finalObject.getString("rqstLng");
} catch (JSONException e) {
e.printStackTrace();
}
}
});
taskDetails.execute("http://10.0.2.2/wingman/requestDetails.php");
onMapReady
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
LatLng location = new LatLng(Double.valueOf(lat1), Double.valueOf(lng1));
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(location, 15);
mGoogleMap.moveCamera(update);
MarkerOptions options = new MarkerOptions()
.position(location)
.snippet("I'm around here!!!");
CircleOptions circle = new CircleOptions()
.center(location)
.radius(2000)
.fillColor(0x55add8e6)
.strokeColor(Color.BLUE)
.strokeWidth(2);
mGoogleMap.addCircle(circle);
mGoogleMap.addMarker(options);
}

There is no way to guarantee that your async task could complete before the Google map's onMapReady() were called. Instead, I propose that you make the REST call for map information from the onMapReady() method itself. This way, you can be sure that when the callback is fired, there is an actual live Google map handle to which you could assign a marker etc.
Here is a skeleton of what the code might look like:
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
new YourAsyncTask(this).execute();
}
Then in your async task you can parse the data and assign the marker to your Google Map.

I think you have to make a function for what ever task you want to perform on map basis on user experience and pass parameter related which value you need to perform your task on map like latitude longitude.
private void yourFunctionName(double lat1, double lng1){
LatLng location = new LatLng(Double.valueOf(lat1), Double.valueOf(lng1));
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(location, 15);
mGoogleMap.moveCamera(update);
MarkerOptions options = new MarkerOptions()
.position(location)
.snippet("I'm around here!!!");
CircleOptions circle = new CircleOptions()
.center(location)
.radius(2000)
.fillColor(0x55add8e6)
.strokeColor(Color.BLUE)
.strokeWidth(2);
mGoogleMap.addCircle(circle);
mGoogleMap.addMarker(options);
}
you not need to perform any task in onMapReady() function
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
}
store only google map object
mGoogleMap = googleMap;
now perform network operation and call which function you want to perform
HashMap<String, String> postData = new HashMap<>();
postData.put("rqstID", rqstID);
AsyncClass taskDetails = new AsyncClass(AcceptActivity.this, postData,
"Getting details", new AsyncResponse() {
#Override
public void processFinish(String s) {
Log.d("AcceptActivity", s);
JSONObject parentObject = null;
try {
parentObject = new JSONObject(s);
JSONArray parentArray = parentObject.getJSONArray("result");
JSONObject finalObject = parentArray.getJSONObject(0);
lat1 = finalObject.getString("rqstLat");
lng1 = finalObject.getString("rqstLng");
yourFunctionName(Lat1, lng1) // CALL THIS AFTER GETED RESULT
} catch (JSONException e) {
e.printStackTrace();
}
}
});
taskDetails.execute("http://10.0.2.2/wingman/requestDetails.php");

Adding Async in onMapReady() won't help, instead replace somefragment.getMapAsync(this) with your Async task call and add somefragment.getMapAsync(this) in the end of onPostExecute.

Related

Can't return location from one activity to another

I am trying to fetch latitude and longitude from mysql database using AsyncTask and show it on Map.I have created a class which gets the location from database
here is the method which returns the location from database
public Location addEmployee() {
class AddEmployee extends AsyncTask<Void, Void, String> {
//ProgressDialog loading;
/* #Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Retreiving...", "Wait...", false, false);
}*/
#Override
protected void onPostExecute(String success) {
// super.onPostExecute(success);
//loading.dismiss();
try {
parseJSON(success);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... v) {
HashMap<String, String> params = new HashMap<>();
params.put("busid", busid);
RequestHandler rh = new RequestHandler();
String res = rh.sendPostRequest("https://tkajbaje.000webhostapp.com/php/busid.php", params);
return res;
}
public void parseJSON(final String success) throws JSONException {
JSONObject jsonObject;
jsonObject = new JSONObject(success);
if (jsonObject.has("Latitude")) {
location.setLatitude(Double.valueOf(jsonObject.getString("Latitude")));
}
if (jsonObject.has("Longitude")) {
location.setLongitude(Double.valueOf(jsonObject.getString("Longitude")));
}
}
}
AddEmployee ae = new AddEmployee();
ae.execute();
return(location);
}
I have another activity which gets the location from the above function and shows it on map.here is the code
public void onMapReady(GoogleMap googleMap) {
// Add a marker in Sydney, Australia,
// and move the map's camera to the same location.
Bundle extras = getIntent().getExtras();
String busid=String.valueOf(1);
Location location;
MainActivity activity=new MainActivity(busid);
location=activity.addEmployee();
double Latitude=location.getLatitude();
Toast.makeText(MapsMarkerActivity.this,String.valueOf(Latitude), Toast.LENGTH_LONG).show();
double Longitude=location.getLongitude();
LatLng sydney = new LatLng(Latitude, Longitude);
googleMap.addMarker(new MarkerOptions().position(sydney)
.title("Bus location"));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
But the latitude and longitude always happen to be 0.0.
Cuz, it starts the AsyncTask and return the location object(whatever the state of that object is). it will not wait for AsyncTask to complete the execution.
Solution:-
You can create an interface in that class and execute in onPostExecute() implement the Interface in activity or use it Anonymously with Class object. Now, whenever it callbacks you can do rest of the work.
I don't see where the location is defined, however it looks like you are mixing asynchronous and synchronous code.
AddEmployee ae = new AddEmployee();
ae.execute();
return(location);
In this part, you invoke an asynchronous task which will assign location a new value if the task is successful, however the keyword here is asynchronous, here location will return before Async Task is completed. You can create a Listener and call it in onPostExecute.
MainActivity activity=new MainActivity(busid);
location=activity.addEmployee();
Here, I strongly recommend making a new class and putting addEmployee there (and other logic that is not specific to the Activity). Creating a new activity with new keyword is not a good approach.

Extract data from WAMP sql server database to Android App

My aim is to draw markers based on GPS coordinates received from the WAMP server. I am not being able to draw the markers, what should I improve in my code in order to do so?
The following is the code responsible of getting data from a database running on WAMP server and drawing the markers on the map:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private RequestQueue requestQueue;
private double lat;
private double lon;
private int flag;
private String showUrl = "http://<<LOCAL-IP-ADDRESS>/directory/showSensor.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready
// to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, showUrl,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray sensorLocations = response.getJSONArray("Sensor Locations");
for (int i = 0; i < sensorLocations.length(); i++) {
JSONObject sensorLocation = sensorLocations.getJSONObject(i);
String latitude = sensorLocation.getString("lat");
String longitude = sensorLocation.getString("long");
String flg = sensorLocation.getString("flag");
if (flag == 1) {
lat = Double.parseDouble(latitude);
lon = Double.parseDouble(longitude);
flag = 0;
}
}
;
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);
}
/**
* Manipulates the map once available. This callback is triggered when the
* map is ready to be used. This is where we can add markers or lines, add
* listeners or move the camera. In this case, we just add a marker near
* Sydney, Australia. If Google Play services is not installed on the
* device, the user will be prompted to install it inside the
* SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sensor = new LatLng(lat, lon);
mMap.addMarker(new MarkerOptions().position(sensor).title(lat + "," + lon));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sensor));
}
}
It seems that the onMapReady method gets called before you receive a response from your server. Move the code to request data from your server to the onMapReady method:
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
showUrl, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray sensorLocations = response.getJSONArray("Sensor Locations");
for (int i = 0; i < sensorLocations.length(); i++) {
JSONObject sensorLocation = sensorLocations.getJSONObject(i);
String latitude = sensorLocation.getString("lat");
String longitude= sensorLocation.getString("long");
String flg = sensorLocation.getString("flag");
if(flag ==1 ) {
lat = Double.parseDouble(latitude);
lon = Double.parseDouble(longitude);
flag=0;
LatLng sensor = new LatLng(lat, lon);
mMap.addMarker(new MarkerOptions().position(sensor).title(lat+ " " + lon));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sensor));
}
}
;
}catch(JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);
}

How to display marker on given Latitude and longitude values using google map in android?

I am developing an app using google map.In this i want to show google map of provided values of latitude and longitude.In app i fetch the latitude and longitude values from database and at this values of latitude and longitude i want to show marker on google map.
Following is the code which i used, In below code i show fetched values of latitude and longitude and also marker show on this fetch values of latitude and longitude on google map but the problem is when i run the app first time map show accurately at fetched values of latitude and longitude but when i open the app second time it shows blue on map.I want to show map at fetched values of latitude and longitude.How do i do this?
//java code
public class Location_Track6 extends FragmentActivity {
JSONArray result = null;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String CON = "CON";
JSONObject jsonobject;
JSONArray jsonarray;
SupportMapFragment fm;
private String url ="";
private static final String TAG_USER = "result";
// private static final String TAG_SNAME = "pseats";
private static final String TAG_LONG = "longitude";
private static final String TAG_LAT = "latitude";
private static final String TAG_ADDRESS = "paddress";
private List<LatLng> points = new ArrayList<>();
Polyline line; //added
TextView tv_mobno, tv_latitude, tv_longitude, tv_time;
String getLatitude;
String getLongitude;
Button slocation;
TextView etLng, etLat;
Button btnShow;
double lati=0;
double lngi=0;
GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location_track6);
tv_mobno=(TextView)findViewById(R.id.textView_mob);
tv_latitude=(TextView)findViewById(R.id.textView_latitude);
tv_longitude=(TextView)findViewById(R.id.textView_longitude);
tv_time=(TextView)findViewById(R.id.textView_time);
etLat = (TextView) findViewById(R.id.et_lat);
etLng = (TextView) findViewById(R.id.et_lng);
fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
// slocation=(Button)findViewById(R.id.button_slocation);
url = "http://example.in/gmap_track.php";
// Getting reference to button btn_show
btnShow = (Button) findViewById(R.id.btn_show);
new JSONParse().execute();
// Setting click event listener for the button
btnShow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getUserLocation();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Location_Track6.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array
result = json.getJSONArray(TAG_USER);
JSONObject c = result.getJSONObject(0);
// Storing JSON item in a Variable
String lat = c.getString(TAG_LAT);
String lng = c.getString(TAG_LONG);
//Set JSON Data in TextView
etLat.setText(lat);
etLng.setText(lng);
lati = Double.parseDouble(etLat.getText().toString());
lngi = Double.parseDouble(etLng.getText().toString());
// MarkerOptions marker = new MarkerOptions().position(new LatLng(lati, lng)).title("point");
// googleMap.addMarker(marker);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private void getUserLocation(){
LatLng position = new LatLng(lati, lngi);
// 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:"+lati+",Longitude:"+lngi);
// Getting Reference to SupportMapFragment of activity_map.xml
// Getting reference to google map
googleMap = fm.getMap();
// Adding Marker on the Google Map
googleMap.addMarker(options);
// Creating CameraUpdate object for position
CameraUpdate updatePosition = CameraUpdateFactory.newLatLng(position);
// Creating CameraUpdate object for zoom
CameraUpdate updateZoom = CameraUpdateFactory.zoomBy(13);
// Updating the camera position to the user input latitude and longitude
googleMap.moveCamera(updatePosition);
// Applying zoom to the marker position
googleMap.animateCamera(updateZoom);
}
private void addMarker() {
MarkerOptions options = new MarkerOptions();
// following four lines requires 'Google Maps Android API Utility Library'
// https://developers.google.com/maps/documentation/android/utility/
// I have used this to display the time as title for location markers
// you can safely comment the following four lines but for this info
/* IconGenerator iconFactory = new IconGenerator(this);
iconFactory.setStyle(IconGenerator.STYLE_PURPLE);
options.icon(BitmapDescriptorFactory.fromBitmap(iconFactory.makeIcon(String.valueOf(R.drawable.one))));
options.anchor(iconFactory.getAnchorU(), iconFactory.getAnchorV());
*/
LatLng currentLatLng = new LatLng(lati,lngi);
options.position(currentLatLng);
Marker mapMarker = googleMap.addMarker(options);
// long atTime = mCurrentLocation.getTime();
// mLastUpdateTime = DateFormat.getTimeInstance().format(new Date(atTime));
// mapMarker.setTitle(mLastUpdateTime);
mapMarker.setTitle("point");
// Log.d(TAG, "Marker added.............................");
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLatLng,
13));
// Log.d(TAG, "Zoom done.............................");
}
}
For displaying marker by static or give Latitude and Longitude
lat = 22.368025;
lon =91.849106;
loc = new LatLng(lat, lon);
marker = googleMap.addMarker(new MarkerOptions().position(loc).title("Hello Chittagong").snippet("A nice city"));
For changing marker color
marker.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN));`
Zoom in the position
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(loc, 11.0f));

not getting markers on map from corresponding longitude latitude values fetched from MySql

I am trying to plot longitude latitude values from MySql on google map with marker. Code for fetching longitude latitude value is correct as code displays those values while using Toast Message. The problem is that everything goes fine except I can't see any markers on google map. Here is my source code.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private String JSON_STRING;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
getJSON();
/* LatLng sydney = new LatLng(33, 88);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
*/
}
private void showLongLat(){
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
for(int i = 0; i<result.length(); i++){
JSONObject jo = result.getJSONObject(i);
String id = jo.getString(Config.TAG_ID);
String longitude = jo.getString(Config.TAG_LONG);
String latitude = jo.getString(Config.TAG_LAT);
Toast.makeText(getApplicationContext(),latitude+longitude,Toast.LENGTH_LONG).show();
LatLng marker = new LatLng(Double.parseDouble(longitude),Double.parseDouble(latitude));
//LatLng sydney = new LatLng(42+i,87-i);
mMap.addMarker(new MarkerOptions().position(marker).title("Marker Somewhere"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(marker));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private void getJSON(){
class GetJSON extends AsyncTask<Void,Void,String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MapsActivity.this,"Fetching Data","Wait...",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
JSON_STRING = s;
showLongLat();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(Config.URL_GET_ALL);
return s;
}
}
GetJSON gj = new GetJSON();
gj.execute();
}
}
You are changing the values of latitude and longitude. This line:
LatLng marker = new LatLng(Double.parseDouble(longitude),Double.parseDouble(latitude));
Must be:
LatLng marker = new LatLng(Double.parseDouble(latitude),Double.parseDouble(longitude));

How to add multiple markers on a google map parsed from json array?

I have written a program in which on button click i am getting the nearby atms from json . This is the link
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=19.052696,72.8713694&radius=1000&types=atm&sensor=true&key=AIzaSyA8szrI9Ue4EwyUwTgz7Nk0c39qMal0pN4
I want to plot the atms on google map but the problem is only the last atm is being displayed on the map
Code : Method to get the atm names , latitude , longitude and vicinity
public void showAtm(){
String getAtmUrl =
"https://maps.googleapis.com/maps/api/place/nearbysearch/json?
location="+lat+","+lng+"&radius=1000&types=atm&sensor=true
&key=AIzaSyA8szrI9Ue4EwyUwTgz7Nk0c39qMal0pN4";
try{
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().url(getAtmUrl).build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
Map_Activity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getBaseContext(), "Request to atm
locations failed", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onResponse(Call call, Response response) throws
IOException {
Log.i("response ", "onResponse(): " + response);
String result = response.body().string();
Log.i("result",result);
try{
JSONObject jsonObject = new JSONObject(result);
String resultData = jsonObject.getString("results");
JSONArray urlDetails = new JSONArray(resultData);
for (int i = 0 ; i < urlDetails.length(); i++){
JSONObject json = urlDetails.getJSONObject(i);
geometry = json.getString(GOEMETRY);
vicinity = json.getString(VICINITY);
JSONObject jsonGeometry = new JSONObject(geometry);
String geoLocation =
jsonGeometry.getString(LOCATION);
JSONObject jsonLatLng = new JSONObject(geoLocation);
atmLat = jsonLatLng.getDouble(LATITUDE);
atmLong = jsonLatLng.getDouble(LONGITUDE);
atmName = json.getString(ATM_NAME);
Log.i("JsonArrayAtm", "" + atmName);
Log.i("JsonArrayGeometry",geometry);
Log.i("LatLong",""+atmLat+" , "+atmLong);
Log.i("Vicinity", vicinity);
runOnUiThread(new Runnable() {
#Override
public void run() {
moveAtmMap(atmLat ,atmLong );
}
});
}
}catch (Exception e){
e.printStackTrace();
}
}
});
}catch (Exception e){
e.printStackTrace();
}
}
///////////////////////////// atm locations map ///////////////////
private void moveAtmMap(Double amtLatitude,Double atmLongitude){
fragment.getMap().clear();
CameraPosition position = CameraPosition.builder()
.target(new LatLng(amtLatitude, atmLongitude))
.zoom(16f)
.bearing(0.0f)
.tilt(0.0f)
.build();
String msg = amtLatitude+ ", " + atmLongitude;
LatLng latLng = new LatLng(amtLatitude, atmLongitude);
fragment.getMap().addMarker(new MarkerOptions()
.position(latLng));
fragment.getMap().setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter()
{
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
View v = getLayoutInflater().inflate(R.layout.atm_custom_window,
null);
TextView atmHeader = (TextView) v.findViewById(R.id.atmName);
TextView atmLocation = (TextView)
v.findViewById(R.id.atmLocation);
atmHeader.setText(atmName);
atmLocation.setText(vicinity);
return v;
}
});
fragment.getMap().setMapType(GoogleMap.MAP_TYPE_NORMAL);
fragment.getMap().setTrafficEnabled(true);
fragment.getMap().setMyLocationEnabled(true);
fragment.getMap().animateCamera(CameraUpdateFactory
.newCameraPosition(position), null);
}
How do i achieve the above , can anyone suggest me ?
Thanks
You have written the method as,
private void moveAtmMap(Double amtLatitude,Double atmLongitude){
fragment.getMap().clear();
...
}
so every time this method will be called, it will clear all previous markers and you will end up having only the last marker.
Edit
for (int i = 0 ; i < urlDetails.length(); i++){
JSONObject json = urlDetails.getJSONObject(i);
String geometry = json.getString(GOEMETRY);
String vicinity = json.getString(VICINITY);
JSONObject jsonGeometry = new JSONObject(geometry);
String geoLocation = jsonGeometry.getString(LOCATION);
JSONObject jsonLatLng = new JSONObject(geoLocation);
double atmLat = jsonLatLng.getDouble(LATITUDE);
double atmLong = jsonLatLng.getDouble(LONGITUDE);
String atmName = json.getString(ATM_NAME);
runOnUiThread(new Runnable() {
#Override
public void run() {
moveAtmMap(atmLat, atmLong, atmName, vicinity, geometry);
}
});
}
and change method like,
private void moveAtmMap(Double amtLatitude,Double atmLongitude, String name, String vicinity, String geometry)
If you want to clear markers from previous web service hit, then do it before you start adding markers for new service hit, like before the for loop.
Remove this line from the method moveAtmMap:
fragment.getMap().clear();
For the first time, write it before for loop in onResponse.
Try this simple code,
for(int i=0;i<jsonArray.length();i++){
MarkerOptions markerOptions;
markerOptions = new MarkerOptions().position(new LatLng(lattitude,
longitude)
).title("Title").snippet("This is snippet");
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_icon));
marker = googleMap.addMarker(markerOptions);
}
Just replace lattitude,longitude with your values.
If you want to have instance of each marker,then you can put each "marker" object into hashmap with key as marker id. Let me know your feedback.
Note: remove this line - fragment.getMap().clear(); because it will clear map everytime when compiler comes into loop and it will take only last object. this is what happenng right now.

Categories

Resources