I'm making an app to display the five nearest Subway stations. I'm able to get the names of the stations back and populate a list view with the data.
I'm getting lng&lat from the API and would like to add pins to the map using these coordinates. I've got the map working, I'm able to display a single pin, but not multiple pins. A point in the correct direction would be much appreciated - Please see code below.
public class nearMe extends AppCompatActivity implements OnMapReadyCallback {
private MapView mapView;
public GoogleMap gmap;
private static final String MAP_VIEW_BUNDLE_KEY = "MapViewBundleKey";
// Location Co-ordinates
private String lat = "";
private String lng = "";
LocationManager locationManager;
LocationListener locationListener;
private List<Station> stationList = new ArrayList<>();
private RecyclerView recyclerView;
private stationAdapter mAdapter;
/* LOCATION STUFF */
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startListening();
}
}
public void startListening() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
}
}
public void updateLocationInfo(Location location) {
lat = "" + location.getLatitude();
lng = "" + location.getLongitude();
}
#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_location, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// int id = item.getItemId();
getNearestStations();
Toast.makeText(this, "Location Updated!", Toast.LENGTH_SHORT).show();
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_near_me);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mAdapter = new stationAdapter(stationList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
// onClick
recyclerView.addOnItemTouchListener(new TouchListener(getApplicationContext(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
// Toast.makeText(getApplicationContext(), stationList.get(position).getStation() + "", Toast.LENGTH_SHORT).show();
String findStation = stationList.get(position).getStation();
// Toast.makeText(nearMe.this, bob, Toast.LENGTH_SHORT).show();
Uri gmmIntentUri = Uri.parse("google.navigation:q="+findStation+"underground station+London&mode=w");
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
mapIntent.setFlags(mapIntent.FLAG_ACTIVITY_CLEAR_TOP);
if (mapIntent.resolveActivity(getPackageManager()) != null) {
startActivity(mapIntent);
}
}
}));
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
updateLocationInfo(location);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
if (Build.VERSION.SDK_INT < 23) {
startListening();
} else {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
updateLocationInfo(location);
}
}
}
// insert Stations in to recycler
getNearestStations();
//map
Bundle mapViewBundle = null;
if (savedInstanceState != null) {
mapViewBundle = savedInstanceState.getBundle(MAP_VIEW_BUNDLE_KEY);
}
mapView = (MapView) findViewById(R.id.map_view);
mapView.onCreate(mapViewBundle);
mapView.getMapAsync(this);
}
// clear adapter before adding
public void clear() {
int size = this.stationList.size();
this.stationList.clear();
mAdapter.notifyItemRangeRemoved(0, size);
}
public void getNearestStations(){
RequestQueue queue = Volley.newRequestQueue(this);
String url = "https://transportapi.com/v3/uk/tube/stations/near.json?app_id=157c4895&app_key=091697cea8bae89519dd02ebb318fc51&lat=" + lat + "&lon=" + lng + "&rpp=5";
final StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("stations");
// Call 'Clear' method to clear mAdapter before adding new data
clear();
if (jsonArray.length() > 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jObject = jsonArray.getJSONObject(i);
String station = jObject.getString("name");
Station newStation = new Station(station);
stationList.add(newStation);
mAdapter.notifyDataSetChanged();
double longitude = Double.parseDouble(lng);
double latitude = Double.parseDouble(lat);
gmap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.title(station));
}
}else{
Station newStation = new Station("No stations near");
stationList.add(newStation);
mAdapter.notifyDataSetChanged();
// Show a diaog
AlertDialog alertDialog = new AlertDialog.Builder(nearMe.this).create();
alertDialog.setTitle("No Stations Found");
alertDialog.setMessage("You are either not in London or you have no network connectivity.");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}); alertDialog.show();
}
} catch (JSONException e) { }
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
// maps
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Bundle mapViewBundle = outState.getBundle(MAP_VIEW_BUNDLE_KEY);
if (mapViewBundle == null) {
mapViewBundle = new Bundle();
outState.putBundle(MAP_VIEW_BUNDLE_KEY, mapViewBundle);
}
mapView.onSaveInstanceState(mapViewBundle);
}
#Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
#Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
#Override
protected void onPause() {
mapView.onPause();
super.onPause();
}
#Override
protected void onDestroy() {
mapView.onDestroy();
super.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
public void onMapReady(GoogleMap googleMap) {
}
}
Let's say your API returns data in the markers array.
for(int i = 0 ; i < markers.size() ; i++ ) {
createMarker(markers.get(i).getLatitude(), markers.get(i).getLongitude(), markers.get(i).getTitle(), markers.get(i).getSnippet(), markers.get(i).getIconResID());
}
...
protected Marker createMarker(double latitude, double longitude, String title, String snippet, int iconResID) {
return googleMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.anchor(0.5f, 0.5f)
.title(title)
.snippet(snippet);
.icon(BitmapDescriptorFactory.fromResource(iconResID)));
}
Related
hello everyone I am doing a university project and I have to show on google maps the railway stations received from the Server (with a marker and PolylineOptions) and the current position of the user (with a marker). The problem is showing the user's current location (the problem is the code shown in ** bold). My code is:
public class MapsLine extends Fragment {
private String sid_user;
private int did;
GoogleMap map;
private static final int MY_PERMISSION_REQUEST_ACCESS_FINE_LOCATION = 0;
Location currentLocation;
FusedLocationProviderClient fusedLocationProviderClient;
private static final int REQUEST_CODE = 101;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_maps_line, container, false);
**SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
fetchLocation();**
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
map = mMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
MarkerOptions markerOptions = new MarkerOptions().position(latLng).title("I am here!");
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 5));
mMap.addMarker(markerOptions);
mMap.clear();
PolylineOptions polyline1 = new PolylineOptions();
List<LatLng> routeArray = new ArrayList<LatLng>();
JSONObject requestParam = new JSONObject();
String GET_STATIONS = "https://helpme.php";
try {
requestParam.put("did", did);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest req = new JsonObjectRequest(
Request.Method.POST,
GET_STATIONS,
requestParam,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray stations_array = response.getJSONArray("stations");
Log.d("main_activity_sid_map", stations_array.toString());
Log.d("main_activity_sid_map", String.valueOf(stations_array.length()));
for (int j = 0; j < stations_array.length(); j++) {
JSONObject stations = stations_array.getJSONObject(j);
String name = stations.getString("sname");
String lat = stations.getString("lat");
String lon = stations.getString("lon");
Log.d("main_activity_sid_map", name);
Log.d("main_activity_sid_map", lat);
Log.d("main_activity_sid_map", lon);
polyline1.add(new LatLng(Float.parseFloat(lat),Float.parseFloat(lon)));
polyline1.color(Color.RED);
LatLng latLng = new LatLng(Float.parseFloat(lat), Float.parseFloat(lon));
mMap.addMarker(new MarkerOptions().position(latLng).title("Marker in " + name));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
LatLng from_Latlng = new LatLng(Float.parseFloat(lat), Float.parseFloat(lon));
if (!routeArray.contains(latLng)) {
routeArray.add(latLng);
}
}
} catch (Exception e) {
e.printStackTrace();
return;
}
drawLine(routeArray);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
MainActivity.requestQueue.add(req);
}
});
return rootView;
}
**private void fetchLocation() {
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_CODE);
return;
}
Task<Location> task = fusedLocationProviderClient.getLastLocation();
task.addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
currentLocation = location;
Toast.makeText(getActivity().getApplicationContext(), currentLocation.getLatitude() + "" + currentLocation.getLongitude(), Toast.LENGTH_SHORT).show();
SupportMapFragment supportMapFragment = (SupportMapFragment) getParentFragmentManager().findFragmentById(R.id.map);
assert supportMapFragment != null;
supportMapFragment.getMapAsync((OnMapReadyCallback) MapsLine.this);
}
}
});
}**
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case MY_PERMISSION_REQUEST_ACCESS_FINE_LOCATION:
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted
Log.d("Location", "Now the permission is granted");
} else {
// permission was not granted
Log.d("Location", "Permission still not granted");
}
break;
}
}
public void drawLine(List<LatLng> points) {
if (points == null) {
Log.e("Draw Line", "got null as parameters");
return;
}
Polyline line = map.addPolyline(new PolylineOptions().color(Color.RED));
line.setPoints(points);
LatLngBounds.Builder builder = new LatLngBounds.Builder();
}
}
My code does not start. How can I implement the current position of the user and the positions of the stations, received from the server?
I've a very strange problem with using google map in my application , I've build an application , it shows the map in my phone and it has not problem but it doesn't show in another phone , it has a white screen like this :
and then it shows this:
on the same phone, in another app it shows map with no problem .
could you help me ?
this is my code :
public class Maps extends AppCompatActivity {
FetchCordinates fetchCordinates;
Intent locatorService = null;
MapView mMapView;
private GoogleMap googleMap;
Double lat = 0.0, lon = 0.0;
Typeface typeface;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps);
typeface = Func.getTypeFace(this);
mMapView = (MapView) findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume(); // needed to get the map to display immediately
mapBuilder();
try {
Bundle bl = getIntent().getExtras();
if (bl != null) {
lat =(bl.getDouble("lat"));
lon = (bl.getDouble("lon"));
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
mMapView.setVisibility(View.VISIBLE);
// For dropping a marker at a point on the Map
LatLng sydney = new LatLng(lat, lon);
googleMap.addMarker(new MarkerOptions().position(sydney).title(""));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(sydney, 17));
// For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
});
}
} catch (Exception e) {
}
}
private void mapBuilder() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& checkSelfPermission(
android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& checkSelfPermission(
android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(Maps.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
doGPS();
}
} catch (Exception e) {
MyToast.makeText(Maps.this, e.getMessage());
e.printStackTrace();
}
Button mapbutton=(Button)findViewById(R.id.mapbutton);
mapbutton.setTypeface(typeface);
mapbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences settings = getSharedPreferences("settings", MODE_PRIVATE);
SharedPreferences.Editor pref= settings.edit();
pref.putString("lat", lat+"");
pref.putString("lon", lon+"");
pref.commit();
onBackPressed();
}
});
}
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mapBuilder();
} else {
MyToast.makeText(Maps.this, "دسترسی به جی پی اس غیرفعال است");
}
return;
}
}
}
public boolean stopService() {
if (this.locatorService != null) {
this.locatorService = null;
}
return true;
}
public boolean startService() {
try {
FetchCordinates fetchCordinates = new FetchCordinates();
fetchCordinates.execute();
return true;
} catch (Exception error) {
return false;
}
}
public AlertDialog CreateAlert(String title, String message) {
AlertDialog alert = new AlertDialog.Builder(this).create();
alert.setTitle(title);
alert.setMessage(message);
return alert;
}
public class FetchCordinates extends AsyncTask<String, Integer, String> {
AlertDialog.Builder a;
AlertDialog dialog;
public double lati = 0.0;
public double longi = 0.0;
public LocationManager mLocationManager;
public VeggsterLocationListener mVeggsterLocationListener;
#Override
protected void onPreExecute() {
mVeggsterLocationListener = new VeggsterLocationListener();
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0,
mVeggsterLocationListener);
}
#Override
protected void onCancelled() {
System.out.println("Cancelled by user!");
dialog.dismiss();
mLocationManager.removeUpdates(mVeggsterLocationListener);
}
#Override
protected void onPostExecute(String result) {
try {
if(dialog!=null)
dialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
lat = lati;
lon = longi;
MyToast.makeText(Maps.this, "موقعیت شما با موفقیت ثبت شد");
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
mMapView.setVisibility(View.VISIBLE);
// For dropping a marker at a point on the Map
LatLng sydney = new LatLng(lat, lon);
googleMap.addMarker(new MarkerOptions().position(sydney).title(""));
googleMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(sydney, 22));
// For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
});
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
while (this.lati == 0.0) {
}
return null;
}
public class VeggsterLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
int lat = (int) location.getLatitude(); // * 1E6);
int log = (int) location.getLongitude(); // * 1E6);
int acc = (int) (location.getAccuracy());
String info = location.getProvider();
try {
// LocatorService.myLatitude=location.getLatitude();
// LocatorService.myLongitude=location.getLongitude();
lati = location.getLatitude();
longi = location.getLongitude();
} catch (Exception e) {
// progDailog.dismiss();
// Toast.makeText(getApplicationContext(),"Unable to get Location"
// , Toast.LENGTH_LONG).show();
}
}
#Override
public void onProviderDisabled(String provider) {
Log.i("OnProviderDisabled", "OnProviderDisabled");
}
#Override
public void onProviderEnabled(String provider) {
Log.i("onProviderEnabled", "onProviderEnabled");
}
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
Log.i("onStatusChanged", "onStatusChanged");
}
}
}
private void doGPS() {
try {
LocationManager mlocManager = null;
LocationListener mlocListener;
mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
startService();
} else {
android.support.v7.app.AlertDialog.Builder a = new android.support.v7.app.AlertDialog.Builder(Maps.this);
a.setMessage(("جی پی اس خاموش است. آیا میخواهید روشن کنید؟"));
a.setPositiveButton(("بله"), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
}
});
a.setNegativeButton(("خیر"), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
android.support.v7.app.AlertDialog dialog = a.show();
TextView messageText = (TextView) dialog.findViewById(android.R.id.message);
messageText.setGravity(Gravity.RIGHT);
messageText.setTypeface(typeface);
}
} catch (Exception e) {
MyToast.makeText(Maps.this, e.getMessage());
}
}
#Override
protected void onStart() {
super.onStart();
if (mMapView != null && mMapView.getVisibility() == View.VISIBLE)
mapBuilder();
}
could you help me ?
My main class application retrieves data using Retrofit and writes to a POJO ordinary Realm object. Then run the second Activity (MapsActivity) where I set the map, filter the contents of the Realm object for the relevant data. Everything works.
I will add that the Realm object contains over 6600 rows so it is big. And unfortunately I feel I have leaks of memory. Each time you start MapsActivity (going back to MainActivity, selecting another category, and passing it to MapsActivity), the heap looks awful. This is shown in the attached image. I will add that the application works much better when I do not use the Realm object at all, I only do the second Retrofit call in the MapsActivity class. This solution unfortunately doubles my work (in Main and Maps I do exactly the same thing) and I want to avoid this. Maybe someone will see where I have a leak and why the program is slowing down.
My Main:
package com.flex.sklepik;
public class MainActivity extends AppCompatActivity {
List<String> shopsNames;
ArrayList<RowModel> rowModels;
public static final int REQUEST_GOOGLE_PLAY_SERVICES = 1972;
public Realm mRealm;
#BindView(R.id.toolbar_layout)
CollapsingToolbarLayout toolbarLayout;
#BindView(R.id.app_bar)
AppBarLayout appBar;
private ShopsAdapter adapter;
#BindView(R.id.recycler_view)
RecyclerView recyclerView;
private ProgressDialog progressDialog;
private Dialog errorDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
ButterKnife.bind(this);
startRegistrationService();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ConnectionDetector connectionDetector = new ConnectionDetector(this);
if (!connectionDetector.isConnection()) {
finish();
}
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 123);
checkPlayServices();
rowModels = new ArrayList<>();
shopsNames = new ArrayList<>();
Realm.init(this);
mRealm = Realm.getDefaultInstance();
initCollapsingToolbar();
Glide.with(getApplicationContext()).load(R.drawable.shoplogo).
into((ImageView) findViewById(R.id.backdrop));
adapter = new ShopsAdapter(MainActivity.this, shopsNames);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 2);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
AsyncTaskRetro asyncTaskRetro = new AsyncTaskRetro();
asyncTaskRetro.execute();
}
private boolean checkPlayServices() {
GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
int resultCode = googleApiAvailability.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (googleApiAvailability.isUserResolvableError(resultCode)) {
if (errorDialog == null) {
errorDialog = googleApiAvailability.getErrorDialog(this, resultCode, 2404);
errorDialog.setCancelable(false);
}
if (!errorDialog.isShowing())
errorDialog.show();
}
}
return resultCode == ConnectionResult.SUCCESS;
}
private class AsyncTaskRetro extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Czekaj...");
progressDialog.show();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.hide();
}
#Override
protected Void doInBackground(Void... voids) {
PlacesAPI.Factory.getInstance().getPlaces().enqueue(new Callback<Places>() {
#Override
public void onResponse(Call<Places> call, Response<Places> response) {
for (int i = 0; i < response.body().getPosts().size(); i++) {
RowModel rowModel = new RowModel(response.body().getPosts().get(i).getNazwa(),
Double.parseDouble(response.body().getPosts().get(i).getSzer()),
Double.parseDouble(response.body().getPosts().get(i).getDlug()));
rowModels.add(rowModel);
}
String oldName;
oldName = rowModels.get(0).getName();
shopsNames.add(rowModels.get(0).getName());
mRealm.beginTransaction();
mRealm.copyToRealm(rowModels);
mRealm.commitTransaction();
for (int j = 0; j < rowModels.size(); j++) {
if (rowModels.get(j).getName().equals(oldName)) {
continue;
}
oldName = rowModels.get(j).getName();
shopsNames.add(rowModels.get(j).getName());
}
//sortowanie listy z nazwami sklepow
Collections.sort(shopsNames);
recyclerView.setAdapter(adapter);
}
#Override
public void onFailure(Call<Places> call, Throwable t) {
}
});
return null;
}
}
#Override
protected void onResume() {
recyclerView.setAdapter(adapter);
super.onResume();
}
private void initCollapsingToolbar() {
final CollapsingToolbarLayout collapsingToolbar =
(CollapsingToolbarLayout) findViewById(R.id.toolbar_layout);
collapsingToolbar.setTitle(" ");
AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.app_bar);
appBarLayout.setExpanded(true);
// hiding & showing the title when toolbar expanded & collapsed
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
boolean isShow = false;
int scrollRange = -1;
#Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (scrollRange == -1) {
scrollRange = appBarLayout.getTotalScrollRange();
}
if (scrollRange + verticalOffset == 0) {
collapsingToolbar.setTitle(getString(R.string.app_name));
isShow = true;
} else if (isShow) {
collapsingToolbar.setTitle(" ");
isShow = false;
}
}
});
}
private void startRegistrationService() {
GoogleApiAvailability api = GoogleApiAvailability.getInstance();
int code = api.isGooglePlayServicesAvailable(this);
if (code == ConnectionResult.SUCCESS) {
onActivityResult(REQUEST_GOOGLE_PLAY_SERVICES, Activity.RESULT_OK, null);
} else if (api.isUserResolvableError(code) &&
api.showErrorDialogFragment(this, code, REQUEST_GOOGLE_PLAY_SERVICES)) {
// wait for onActivityResult call (see below)
} else {
Toast.makeText(this, api.getErrorString(code), Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_GOOGLE_PLAY_SERVICES:
if (resultCode == Activity.RESULT_OK) {
}
break;
default:
super.onActivityResult(requestCode, resultCode, data);
}
}
}
Map Class:
public class MapActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMarkerClickListener
{
private GoogleMap mMap;
private double naviLat, naviLong;
private double latitude, longitude;
private GoogleApiClient mGoogleApiClient;
#BindView(R.id.adView)
AdView adView;
#BindView(R.id.butnavi)
ImageButton butnavi;
private Location location;
private RealmResults<RowModel> rowModels;
private String shopName;
private Bundle bundle;
private Realm realm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map2);
ButterKnife.bind(this);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(map);
mapFragment.getMapAsync(this);
bundle = getIntent().getExtras();
shopName = bundle.getString("shopName");
mapFragment.getMapAsync(this);
ActivityCompat.requestPermissions(MapActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 123);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
realm = Realm.getDefaultInstance();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnMarkerClickListener(this);
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Uprawnienia nie przyznane", Toast.LENGTH_SHORT).show();
}
mMap.setMyLocationEnabled(true);
cameraMove();
//po wczytaniu mapy wyciągnij dane z bazy sklepów
realmDatabaseBuild();
}
private void addMarker(double lat, double lon) {
mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lon)));
}
#OnClick(R.id.butnavi)
public void btnNavi() {
if (naviLat + naviLong == 0)
Toast.makeText(this,
"Najpierw wybierz market", Toast.LENGTH_SHORT)
.show();
else {
Intent i = new Intent(Intent.ACTION_VIEW, Uri
.parse("google.navigation:q=" + naviLat + ","
+ naviLong));
startActivity(i);
finish();
System.exit(0);
}
}
private void moveCameraToActualPosition(double lat, double lon) {
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(lat, lon))
.zoom(12).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
private void realmDatabaseBuild() {
rowModels = realm.where(RowModel.class).equalTo("name", shopName).findAll();
if (!rowModels.isEmpty()) {
for (int i = 0; i < rowModels.size(); i++) {
addMarker(rowModels.get(i).getLongitude(), rowModels.get(i).getLattitude());
}
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.mapTypeNormal:
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
break;
case R.id.mapTypeSatellite:
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
break;
case R.id.mapTypeTerrain:
mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
break;
case R.id.mapTypeHybrid:
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onBackPressed() {
super.onBackPressed();
mMap.clear();
rowModels = null;
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public boolean onMarkerClick(Marker marker) {
LatLng gps = marker.getPosition();
//ustawienie lat i long dla nawigacji
naviLat = gps.latitude;
naviLong = gps.longitude;
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses;
try {
addresses = geocoder.getFromLocation(gps.latitude, gps.longitude, 1);
String adres = addresses.get(0).getAddressLine(0);
Toast.makeText(this, "Adres: " + adres, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
public void cameraMove() {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Uprawnienia nie przyznane", Toast.LENGTH_SHORT).show();
}
Location myLocation = locationManager.getLastKnownLocation(provider);
if (myLocation != null) {
LatLng ll = new LatLng(myLocation.getLatitude(), myLocation.getLongitude());
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(ll)
.zoom(11).build();
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
} else {
LatLng ll = new LatLng(52.230625, 21.013129);//WAWA
CameraPosition cp = new CameraPosition.Builder()
.target(ll)
.zoom(10).build();
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cp));
}
}
}
And Pojo:
public class RowModel extends RealmObject {
#Required
private String name;
#Required
private Double lattitude, longitude;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getLattitude() {
return lattitude;
}
public void setLattitude(Double lattitude) {
this.lattitude = lattitude;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
public RowModel(String name, Double lattitude, Double longitude) {
this.name = name;
this.lattitude = lattitude;
this.longitude = longitude;
}
public RowModel() {
}
}
I am creating bus tracking android app and below code in working fine. Now what I want that when bus move from one place to another and I am getting new latitude and longitude of bus from m web service so bus showing on new position but its not removing from old place. And same happening for user current location. I want to clear old position of user and bus every 15 seconds. How can I achieve this ?
public class MapActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, OnMapReadyCallback, DirectionFinderListener {
private SQLiteHandler db;
private SessionManager session;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
PendingResult<LocationSettingsResult> result;
final static int REQUEST_LOCATION = 199;
ImageView btnPreference, btnLocation, btnPassword, btnProfile;
Spinner spinnerShift, spinnerStops;
List<String> ShiftArrayList = new ArrayList<String>();
final List<Integer> ShiftValueArrayList = new ArrayList<Integer>();
List<String> StopArrayList = new ArrayList<String>();
final List<Integer> StopValueArrayList = new ArrayList<Integer>();
int selected_shift, selected_stop;
GridView gridView;
private List<Routes> routeList = new ArrayList<Routes>();
private CustomListAdapter adapter;
GPSTracker gps;
List<Marker> originMarkers = new ArrayList<>();
List<Marker> currentLoc = new ArrayList<>();
List<Marker> MyLocation1 = new ArrayList<>();
List<Marker> waypointsMarkers = new ArrayList<>();
GoogleMap mMap;
List<Marker> buslocation = new ArrayList<>();
List<Marker> destinationMarkers = new ArrayList<>();
List<Polyline> polylinePaths = new ArrayList<>();
android.os.Handler handler;
boolean doubleBackToExitPressedOnce = false;
ConnectionDetector cd;
Boolean isInternetPresent = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
FindViewById();
CheckGpsStatus();
ButtonCLickEvent();
}
public void FindViewById() {
btnPreference = (ImageView) findViewById(R.id.btnPreference);
btnLocation = (ImageView) findViewById(R.id.btnLocation);
btnPassword = (ImageView) findViewById(R.id.btnPassword);
btnProfile = (ImageView) findViewById(R.id.btnProfile);
spinnerShift = (Spinner) findViewById(R.id.spinnerShift);
spinnerStops = (Spinner) findViewById(R.id.spinnerStops);
gridView = (GridView) findViewById(R.id.gridView);
}
public void ButtonCLickEvent() {
btnPreference.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MapActivity.this, SetPreferenceActivity.class);
startActivity(intent);
}
});
btnPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MapActivity.this, ResetPasswordActivity.class);
startActivity(intent);
}
});
btnProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MapActivity.this, ProfileActivity.class);
startActivity(intent);
}
});
}
public void CheckGpsStatus() {
final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
cd = new ConnectionDetector(getApplicationContext());
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent){
apiShift();
}else {
final SweetAlertDialog alert = new SweetAlertDialog(MapActivity.this, SweetAlertDialog.WARNING_TYPE);
alert.setTitleText("No Internet");
alert.setContentText("Please connect to internet..");
alert.show();
}
handler = new Handler();
handler.postDelayed(runLocation, 15000);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
} else {
apiShift();
handler = new Handler();
handler.postDelayed(runLocation, 15000);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
}
public void apiShift() {
VolleyWebService.makeJsonObjectRequest(MapActivity.this, Request.Method.GET, AppConfig.ShiftData, null, new VolleyResponseListener() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject jObj = new JSONObject(String.valueOf(response));
JSONArray json_user = jObj.getJSONArray("Message");
for (int i = 0; i < json_user.length(); i++) {
try {
JSONObject obj = json_user.getJSONObject(i);
ShiftArrayList.add(obj.getString("shift_name"));
ShiftValueArrayList.add(Integer.valueOf(obj.getString("shift_id")));
} catch (JSONException e) {
e.printStackTrace();
}
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(MapActivity.this, R.layout.spinner, ShiftArrayList);
dataAdapter.notifyDataSetChanged();
spinnerShift.setAdapter(dataAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onError(String message) {
Toast.makeText(MapActivity.this, "Server not responding..", Toast.LENGTH_SHORT).show();
}
});
spinnerShift.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selected_shift = Integer.parseInt(ShiftValueArrayList.get(position).toString());
String shift_id = ShiftValueArrayList.get(position).toString();
apiRoutes(shift_id);
apiStops(shift_id);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void apiStops(final String shiftId) {
String url = AppConfig.StopData + "shift_id=" + shiftId;
VolleyWebService.makeJsonObjectRequest(MapActivity.this, Request.Method.GET, url, null, new VolleyResponseListener() {
#Override
public void onResponse(JSONObject response) {
try {
StopArrayList.clear();
StopValueArrayList.clear();
JSONObject jObj = new JSONObject(String.valueOf(response));
JSONArray json_user = jObj.getJSONArray("Message");
for (int i = 0; i < json_user.length(); i++) {
try {
JSONObject obj = json_user.getJSONObject(i);
StopArrayList.add(obj.getString("stop_name"));
StopValueArrayList.add(Integer.valueOf(obj.getString("stop_id")));
} catch (JSONException e) {
e.printStackTrace();
}
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(MapActivity.this, R.layout.spinner_stop, StopArrayList);
dataAdapter.notifyDataSetChanged();
spinnerStops.setAdapter(dataAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onError(String message) {
Toast.makeText(MapActivity.this, "Server not responding..", Toast.LENGTH_SHORT).show();
}
});
spinnerStops.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selected_stop = Integer.parseInt(StopValueArrayList.get(position).toString());
String stop_id = StopValueArrayList.get(position).toString();
apiDrawRoute(shiftId, stop_id);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void apiRoutes(String shift_id) {
String url = AppConfig.RouteData + "shift_id_tabular=" + shift_id;
VolleyWebService.makeJsonObjectRequest(MapActivity.this, Request.Method.GET, url, null, new VolleyResponseListener() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject mainObj = new JSONObject(String.valueOf(response));
if (mainObj != null) {
routeList.clear();
JSONArray list = mainObj.getJSONArray("Message");
if (list != null) {
for (int i = 0; i < list.length(); i++) {
JSONObject elem = list.getJSONObject(i);
Routes routes = new Routes();
routes.setSrNo(elem.getString("rn"));
routes.setName(elem.getString("location"));
routes.setTime(elem.getString("actual_time"));
routes.setStatus(elem.getString("run_status"));
routeList.add(routes);
}
}
}
}
adapter = new CustomListAdapter(MapActivity.this, routeList);
gridView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onError(String message) {
Toast.makeText(MapActivity.this, "Server not responding", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(30 * 1000);
mLocationRequest.setFastestInterval(5 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest);
builder.setAlwaysShow(true);
result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
status.startResolutionForResult(
MapActivity.this,
REQUEST_LOCATION);
} catch (IntentSender.SendIntentException e) {
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
break;
}
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d("onActivityResult()", Integer.toString(resultCode));
switch (requestCode) {
case REQUEST_LOCATION:
switch (resultCode) {
case Activity.RESULT_OK: {
break;
}
case Activity.RESULT_CANCELED: {
finish();
break;
}
default: {
break;
}
}
break;
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.logout:
db = new SQLiteHandler(getApplicationContext());
session = new SessionManager(getApplicationContext());
session.setLogin(false);
db.deleteUsers();
Intent intent = new Intent(MapActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
return true;
}
public void apiDrawRoute(String shiftId, String stopId) {
String url = AppConfig.RouteData + "shiftid=" + shiftId + "&stopid=" + stopId;
VolleyWebService.makeJsonObjectRequest(MapActivity.this, Request.Method.GET, url, null, new VolleyResponseListener() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject jObj = new JSONObject(String.valueOf(response));
JSONArray json_user = jObj.getJSONArray("Message");
for (int i = 0; i < json_user.length(); i++) {
try {
JSONObject obj = json_user.getJSONObject(i);
List<String> wp = new ArrayList<String>();
for (int w1 = 0; w1 < json_user.length(); w1++) {
wp.add(obj.getString("waypoints_latitude") + ',' + obj.getString("waypoints_longitude") + '|');
}
sendRequest(obj.getString("start_location"), obj.getString("end_location"), wp);
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onError(String message) {
Toast.makeText(MapActivity.this, "Server not responding..", Toast.LENGTH_SHORT).show();
}
});
spinnerShift.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selected_shift = Integer.parseInt(ShiftValueArrayList.get(position).toString());
String shift_id = ShiftValueArrayList.get(position).toString();
apiRoutes(shift_id);
apiStops(shift_id);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.clear();
MyLocation1.clear();
gps = new GPSTracker(MapActivity.this);
if (gps.CanGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
LatLng mylocation = new LatLng(latitude, longitude);
if (MyLocation1 != null) {
for (Marker marker : MyLocation1) {
marker.remove();
}
}
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mylocation, 10));
MyLocation1.add(mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.curr_location))
.title("My Location")
.position(mylocation)));
Circle circle = mMap.addCircle(new CircleOptions()
.center(mylocation)
.radius(1000)
.strokeColor(0x10000000)
.fillColor(0x10000000));
} else {
//gps.showSettingsAlert();
}
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
}
public Runnable runLocation = new Runnable() {
#Override
public void run() {
gps = new GPSTracker(MapActivity.this);
MyLocation1.clear();
if (gps.CanGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
LatLng mylocation = new LatLng(latitude, longitude);
if (MyLocation1 != null) {
for (Marker marker : MyLocation1) {
marker.remove();
}
}
MyLocation1.add(mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.curr_location))
.title("My Location")
.position(mylocation)));
Circle circle = mMap.addCircle(new CircleOptions()
.center(mylocation)
.radius(1000)
.strokeColor(0x10000000)
.fillColor(0x10000000));
} else {
// gps.showSettingsAlert();
}
String tag_json_obj = "json_obj_req";
String url = AppConfig.RouteData + "i=1&" + "y=1";
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject jObj = new JSONObject(String.valueOf(response));
JSONArray json_user = jObj.getJSONArray("Message");
currentLoc.clear();
for (int i = 0; i < json_user.length(); i++) {
try {
JSONObject obj = json_user.getJSONObject(i);
Double currLat = obj.getDouble("actual_lat");
Double currLong = obj.getDouble("actual_long");
LatLng hcmus = new LatLng(currLat, currLong);
currentLoc.add(mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.bus))
.title("Bus No" + obj.getString("bus_id"))
.position(hcmus)));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MapActivity.this, "Server not responding..", Toast.LENGTH_SHORT).show();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
MapActivity.this.handler.postDelayed(MapActivity.this.runLocation, 15000);
}
};
private void sendRequest(String Sl, String El, List Wp) {
String origin = Sl.toString();
String destination = El.toString();
List waypoints = Wp;
if (origin.isEmpty()) {
Toast.makeText(this, "Please enter origin address!", Toast.LENGTH_SHORT).show();
return;
}
if (destination.isEmpty()) {
Toast.makeText(this, "Please enter destination address!", Toast.LENGTH_SHORT).show();
return;
}
try {
new DirectionFinder(MapActivity.this, origin, destination, waypoints).execute();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
#Override
public void onDirectionFinderStart() {
if (originMarkers != null) {
for (Marker marker : originMarkers) {
marker.remove();
}
}
if (destinationMarkers != null) {
for (Marker marker : destinationMarkers) {
marker.remove();
}
}
if (polylinePaths != null) {
for (Polyline polyline : polylinePaths) {
polyline.remove();
}
}
}
#Override
public void onDirectionFinderSuccess(List<Route> routes) {
polylinePaths = new ArrayList<>();
originMarkers = new ArrayList<>();
destinationMarkers = new ArrayList<>();
waypointsMarkers = new ArrayList<>();
buslocation = new ArrayList<>();
mMap.clear();
for (Route route : routes) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(route.startLocation, 16));
((TextView) findViewById(R.id.tvDuration)).setText(route.duration.text);
((TextView) findViewById(R.id.tvDistance)).setText(route.distance.text);
originMarkers.add(mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
.title(route.startAddress)
.position(route.startLocation)));
// waypointsMarkers.add(mMap.addMarker(new MarkerOptions()
// .icon(BitmapDescriptorFactory.fromResource(R.drawable.end_green))
// .title(route.waypointsAddress)
// .position(route.waypointsLocation)));
for (int i = 0; i < route.jlegs.size(); i++) {
destinationMarkers.add(mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE))
.title(route.jaddress.get(i))
.position(route.jlegs.get(i))));
}
destinationMarkers.add(mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE))
.title(route.endAddress)
.position(route.endLocation)));
// final LatLng MELBOURNE = new LatLng(24.571982, 73.725597);
// buslocation.add(mMap.addMarker(new MarkerOptions()
// .icon(BitmapDescriptorFactory.fromResource(R.drawable.bus))
// .title("Bus Location")
// .position(MELBOURNE)));
// final LatLng MELBOURNE = new LatLng(24.571982, 73.725597);
PolylineOptions polylineOptions = new PolylineOptions().
geodesic(true).
color(Color.BLUE).
width(5);
for (int i = 0; i < route.points.size(); i++)
polylineOptions.add(route.points.get(i));
polylinePaths.add(mMap.addPolyline(polylineOptions));
// setUpMapIfNeeded();
}
}
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
}
Clean and Reload Your Location List On Every Single Update.!
I am working on maps in my application. In which i used InfoWindowAdapter. I am having image view in that. But on opening the info window image is not display.
The xml of infoWindow is as follow:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="4dp"
card_view:contentPadding="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:orientation="horizontal">
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/imageView_infoWindow"
android:layout_width="80dp"
android:layout_height="80dp"
android:scaleType="fitXY"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/textView_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView_address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView_location"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
And the Activity code is as follow:
public class LocationActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleMap.OnMyLocationChangeListener, GoogleMap.OnMyLocationButtonClickListener {
private GoogleMap mMap;
public LatLng MOUNTAIN_VIEW;
int METERS = 20000;
final private int PERMISSION_REQUEST_CODE_FOR_ACCESS_LOCATION = 123;
List<MarkerOptions> markerOptionsList;
ArrayList<ModelLocation> modelLocation;
protected LocationManager locationManager;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
ImageLoader mImageLoader;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setElevation(2);
actionBar.setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(true);
actionBar.setTitle("Location");
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.getUiSettings().setIndoorLevelPickerEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
if (checkPermission()) {
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationChangeListener(this);
} else {
requestPermission();
}
CameraPosition cameraPosition = new CameraPosition.Builder().target(MOUNTAIN_VIEW)
.zoom(17)
.bearing(360)
.tilt(45)
.build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
mMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition cameraPosition) {
final LatLng latLng = cameraPosition.target;
final Location location = new Location("Camera_Location");
location.setLatitude(latLng.latitude);
location.setLongitude(latLng.longitude);
final ProgressDialog progressDialog = new ProgressDialog(LocationActivity.this, R.style.ProgressBarTansparent);
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.show();
progressDialog.setContentView(R.layout.custom_progressbar_layout);
String url = "My URL To Get Data";
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("Key","Value");
} catch (JSONException e) {
e.printStackTrace();
}
final JsonObjectRequest postRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArrayUserList = response.getJSONArray("ABC");
modelLocation = new ArrayList<>();
int size = jsonArrayUserList.length();
if (size > 0) {
for (int count = 0; count < size; count++) {
JSONObject jsonObject = jsonArrayUserList.getJSONObject(count);
int userID = jsonObject.getInt("userID");
String Name = jsonObject.getString("address");
String address = jsonObject.getString("ADD");
float latitude = Float.parseFloat(jsonObject.getString("latitude"));
float longitude = Float.parseFloat(jsonObject.getString("longitude"));
String image = jsonObject.getString("image");
ModelLocation modelLocation1 = new ModelLocation(userID, Name, address, latitude, longitude, image);
modelLocation.add(modelLocation1);
}
Location target = new Location("target");
for (ModelLocation modelLocation1 : modelLocation) {
target.setLatitude(modelLocation1.latitude);
target.setLongitude(modelLocation1.longitude);
LatLng point = new LatLng(modelLocation1.latitude, modelLocation1.longitude);
MarkerOptions markerOptions = new MarkerOptions().title(modelLocation1.Name).snippet(modelLocation1.address).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_pin)).anchor(0.0f, 1.0f).position(point);
if (location.distanceTo(target) < METERS) {
if (isMarkerOnArray(markerOptionsList, markerOptions)) {
} else {
markerOptionsList.add(markerOptions);
Marker marker = mMap.addMarker(markerOptions);
dropic_pinEffect(marker);
}
}
}
}
progressDialog.dismiss();
} catch (Exception e) {
}
progressDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return headers;
}
};
Volley.newRequestQueue(LocationActivity.this).add(postRequest);
}
});
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
View view = getLayoutInflater().inflate(R.layout.info_window_layout, null);
LatLng latLng = marker.getPosition();
for (int count = 0; count < modelLocation.size(); count++) {
double currentLat = modelLocation.get(count).getLatitude();
double currentLng = modelLocation.get(count).getLongitude();
if ((currentLat == latLng.latitude) && (currentLng == latLng.longitude)) {
TextView textViewTitle = (TextView) view.findViewById(R.id.textView_title);
TextView textViewAddress = (TextView) view.findViewById(R.id.textView_address);
TextView textViewLocation = (TextView) view.findViewById(R.id.textView_location);
final NetworkImageView imageViewUserImage = (NetworkImageView) view.findViewById(R.id.imageView_infoWindow);
textViewTitle.setText("" + modelLocation.get(count).getName());
textViewAddress.setText("" + modelLocation.get(count).getAddress());
textViewLocation.setText(currentLat + ", " + currentLng);
mImageLoader = VolleySingletonClass.getInstance(LocationActivity.this).getImageLoader();
String url = "My URL Of Image";
imageViewUserImage.setImageUrl(url, mImageLoader);
imageViewUserImage.setDefaultImageResId(R.drawable.ic_user_default);
imageViewUserImage.setErrorImageResId(R.drawable.ic_user_default);
}
}
return view;
}
});
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
Intent intent = new Intent(LocationActivity.this, Activity2.class);
startActivity(intent);
finish();
}
});
}
static boolean isMarkerOnArray(List<MarkerOptions> listMarkerOptions, MarkerOptions markerOptions) {
for (int count = 0; count < listMarkerOptions.size(); count++) {
MarkerOptions current = listMarkerOptions.get(count);
if ((current.getPosition().latitude == markerOptions.getPosition().latitude) && (current.getPosition().longitude == markerOptions.getPosition().longitude))
return true;
}
return false;
}
private boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(LocationActivity.this, Manifest.permission.ACCESS_FINE_LOCATION);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(LocationActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)) {
} else {
ActivityCompat.requestPermissions(LocationActivity.this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, PERMISSION_REQUEST_CODE_FOR_ACCESS_LOCATION);
}
}
#SuppressLint("NewApi")
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE_FOR_ACCESS_LOCATION:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationChangeListener(this);
mMap.setOnMyLocationButtonClickListener(this);
} else {
Toast.makeText(LocationActivity.this, "Permission Denied", Toast.LENGTH_LONG).show();
ActivityCompat.requestPermissions(LocationActivity.this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, PERMISSION_REQUEST_CODE_FOR_ACCESS_LOCATION);
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void dropic_pinEffect(final Marker marker) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final long duration = 1000;
final Interpolator interpolator = new BounceInterpolator();
handler.post(new Runnable() {
#Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start;
float t = Math.max(1 - interpolator.getInterpolation((float) elapsed / duration), 0);
marker.setAnchor(0.5f, 1.0f + 7 * t);
if (t > 0.0) {
handler.postDelayed(this, 15);
} else {
}
}
});
}
#Override
public void onMyLocationChange(Location location) {}
#Override
public boolean onMyLocationButtonClick() {
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
#Override
protected void onResume() {
super.onResume();
getLocation();
if (canGetLocation()) {
double lat = getLatitude();
double lng = getLongitude();
MOUNTAIN_VIEW = new LatLng(lat, lng);
markerOptionsList = new ArrayList<MarkerOptions>();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
} else {
showSettingsAlert();
}
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public Location getLocation() {
try {
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
}
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if (isGPSEnabled) {
if (location == null) {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, (LocationListener) this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public double getLatitude() {
double lati = 0;
if (location != null) {
lati = location.getLatitude();
}
return lati;
}
public double getLongitude() {
double longi = 0;
if (location != null) {
longi = location.getLongitude();
}
return longi;
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("GPS is settings");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Intent intent = new Intent(LocationActivity.this, Activity1.class);
startActivity(intent);
finish();
}
});
alertDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
dialog.dismiss();
Intent intent = new Intent(LocationActivity.this, Activity1.class);
startActivity(intent);
finish();
}
});
alertDialog.show();
}
}
I searched on Google that why image is not display, So i got to know that i need to refresh info window adapter may be. Or is it Volley implementation issue?
Please suggest me That my implementation is right or not and what step should i perform to Display Image in image view on window open