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.!
Related
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)));
}
I am having two doubts because today only i started doing projects on google maps my first doubt is
How to calculate distance traveled by user when using google maps ?
like how taxi app is calculating the distance, now let me explain my problem in depth regarding this question i have checkin and check out button in map when user click the checkin button i will take that exact lat and long of that user when user checkout i will fetch the lat and long from where he checked out, after i will send this source latlong and destination latlong to google api this will return the kilometer. But what i need is wherever he traveled he may traveled extra bit of kilometer i need to calculate that also how can i do that.
My second doubt is my google maps taking long time to plot the blue mark in my map it shows searching for gps in notification bar how can i achieve this ?
Below is my complete Code
VisitTravel.java
public class VisitTravel extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private List < LatLng > obj;
private GoogleMap mGoogleMap;
private Double latitue, longtitue, Start_lat, Start_long;
private SupportMapFragment mapFrag;
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private ImageView cancel_bottomsheet;
protected static final int REQUEST_CHECK_SETTINGS = 0x1;
private Bundle bundle;
private ProgressDialog progressDialog;
private String Checkin, parsedDistance, duration, JsonResponse;
private VisitDAO visitDAO;
private Long primaryID;
private ArrayList < LatLng > points;
private Integer id, flag, incidentid, userid;
private TextView heading, duration_textview, dot_source, destination, distance;
private PowerManager.WakeLock wakeLock;
private BottomSheetBehavior bottomSheetBehavior;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_visit_travel);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
mapFrag = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFrag.getMapAsync(this);
InternetCheck internetCheck = new InternetCheck();
boolean check = internetCheck.isNetworkAvailable(VisitTravel.this);
if (!check) {
showAlertDialog();
} else {
createLocationRequest();
buildGoogleApiClient();
Settingsapi();
progressDialog = new ProgressDialog(VisitTravel.this);
// polylineOptions = new PolylineOptions();
cancel_bottomsheet = (ImageView) findViewById(R.id.cancel);
heading = (TextView) findViewById(R.id.heading);
dot_source = (TextView) findViewById(R.id.dot_source);
distance = (TextView) findViewById(R.id.distance);
duration_textview = (TextView) findViewById(R.id.duration);
destination = (TextView) findViewById(R.id.destination);
progressDialog.setMessage("Fetching Location Updates");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.show();
View bottomSheet = findViewById(R.id.bottom_sheet);
LoginDAO loginobj = new LoginDAO(this);
userid = loginobj.getUserID();
bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet);
bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
cancel_bottomsheet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
}
});
bundle = getIntent().getExtras();
if (bundle != null) {
flag = bundle.getInt("flag");
latitue = bundle.getDouble("destination_lat");
longtitue = bundle.getDouble("destination_long");
incidentid = bundle.getInt("incidentid");
if (flag == 1) {
} else {
// time = bundle.getString("checkin");
id = bundle.getInt("id");
incidentid = bundle.getInt("incidentid");
Start_lat = bundle.getDouble("lat");
Checkin = bundle.getString("checkin");
Start_long = bundle.getDouble("long");
String address = bundle.getString("startaddress");
String distance = bundle.getString("estimateddistance");
setBottomSheet(address, distance);
}
}
obj = new ArrayList < > ();
final FloatingActionButton startfab = (FloatingActionButton) findViewById(R.id.start);
final FloatingActionButton stopfab = (FloatingActionButton) findViewById(R.id.stopfab);
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"WakelockTag");
wakeLock.acquire();
visitDAO = new VisitDAO(getApplicationContext());
if (flag == 2) {
startfab.setVisibility(View.INVISIBLE);
}
startfab.setBackgroundResource(R.drawable.ic_play_circle_outline_black_24dp);
final SharedPreferences preferences = getSharedPreferences("lat_long", Context.MODE_PRIVATE);
startfab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mLastLocation != null) {
String checkin_to_server = dateFormat.format(new Date());
Date date = null;
try {
date = dateFormat.parse(checkin_to_server);
} catch (ParseException e) {
e.printStackTrace();
}
String checkin_view = dateview.format(date);
double startinglat = mLastLocation.getLatitude();
double startinglong = mLastLocation.getLongitude();
// String addres=address(startinglat,startinglong);
String jsonresponse = null;
try {
jsonresponse = new GetDistance().execute(startinglat, startinglong, 12.951601, 80.184641).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
ParserTask parserTask = new ParserTask();
if (jsonresponse != null) {
Log.d("responsejson", jsonresponse);
parserTask.execute(jsonresponse);
}
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(jsonresponse);
} catch (JSONException e) {
e.printStackTrace();
}
//Here il save the userlocation in db
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "Please Wait Till We Recieve Location Updates", Toast.LENGTH_SHORT).show();
}
}
});
stopfab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mLastLocation != null) {
double lat = mLastLocation.getLatitude();
double longt = mLastLocation.getLongitude();
String startlat = preferences.getString("startlat", "");
Log.d("startlat", startlat);
String startlong = preferences.getString("startlong", "");
// Calculating distance
String distance = getKilometer(Double.valueOf(startlat), Double.valueOf(startlong), lat, longt);
Intent intent = new Intent(VisitTravel.this, IncidentView.class);
setResult(RESULT_OK, intent);
finish();
} else {
Toast.makeText(getApplicationContext(), "Please Wait Fetching Location", Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
public void onStart() {
super.onStart();
Log.d("start", "onStart fired ..............");
mGoogleApiClient.connect();
}
private void showAlertDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(VisitTravel.this);
builder.setTitle("Network Connectivity")
.setMessage("Please Check Your Network Connectivity")
.setCancelable(false)
.setNegativeButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(getApplicationContext(), IncidentView.class);
setResult(RESULT_OK, intent);
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
#Override
public void onPause() {
super.onPause();
// progressDialog.dismiss();
if (wakeLock.isHeld()) {
wakeLock.release();
}
//stop location updates when Activity is no longer active
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
map_marker_End(12.951601, 80.184641, "Destination");
if (flag == 2) {
map_marker_start(Start_lat, Start_long, Checkin);
}
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
//Location Permission already granted
createLocationRequest();
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
} else {
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000 * 10);
mLocationRequest.setFastestInterval(1000 * 5);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
public void onConnected(Bundle bundle) {
startLocationUpdates();
}
protected void startLocationUpdates() {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
Toast.makeText(this, "LocationNotUpdated", Toast.LENGTH_SHORT).show();
ActivityCompat.requestPermissions(VisitTravel.this,
new String[] {
android.Manifest.permission
.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION
},
20);
} else {
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
Log.d("Loc", "Location update started ..............: ");
// Toast.makeText(this, "LocationUpdatedStart", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onConnectionSuspended(int i) {}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public void map_marker_start(Double lat, Double longt, String title) {
MarkerOptions markerOptions = new MarkerOptions();
LatLng latLng = new LatLng(lat, longt);
Log.d("lat", String.valueOf(latLng.longitude));
markerOptions.position(latLng);
markerOptions.title(title);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
mGoogleMap.addMarker(markerOptions).showInfoWindow();
}
public void map_marker_End(Double lat, Double longt, String title) {
final MarkerOptions markerOptions_end = new MarkerOptions();
LatLng latLng = new LatLng(lat, longt);
Log.d("lat", String.valueOf(latLng.longitude));
markerOptions_end.position(latLng);
markerOptions_end.title(title);
markerOptions_end.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
mGoogleMap.addMarker(markerOptions_end).showInfoWindow();
mGoogleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
String title = marker.getTitle();
if (title.equals("Destination")) {
dot_source.setText("\u2022");
bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
heading.setText("TEST");
duration_textview.setText("Duration:" + " " + duration);
return true;
} else {
bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
return true;
}
}
});
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
PolylineOptions polylineOptions = new PolylineOptions();
Log.d("location", mLastLocation.toString());
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
obj.add(latLng);
polylineOptions.addAll(obj);
polylineOptions.width(9);
polylineOptions.color(Color.parseColor("#2196f3"));
mGoogleMap.addPolyline(polylineOptions);
progressDialog.dismiss();
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(
latLng, 12);
mGoogleMap.animateCamera(cameraUpdate);
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(VisitTravel.this, android.Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
new AlertDialog.Builder(this)
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(VisitTravel.this,
new String[] {
android.Manifest.permission.ACCESS_FINE_LOCATION
},
MY_PERMISSIONS_REQUEST_LOCATION);
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[] {
android.Manifest.permission.ACCESS_FINE_LOCATION
},
MY_PERMISSIONS_REQUEST_LOCATION);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION:
{
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 &&
grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
createLocationRequest();
/// buildGoogleApiClient();
// Settingsapi();
mGoogleMap.setMyLocationEnabled(true);
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
public String getKilometer(final double lat1, final double lon1, final double lat2, final double lon2) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
URL url = new URL("http://maps.googleapis.com/maps/api/directions/json?origin=" + lat1 + "," + lon1 + "&destination=" + lat2 + "," + lon2 + "&sensor=false&units=metric&mode=driving");
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
InputStream in = new BufferedInputStream(conn.getInputStream());
StringBuilder buffer = new StringBuilder();
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader( in ));
String inputLine;
while ((inputLine = reader.readLine()) != null)
buffer.append(inputLine + "\n");
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
Log.e("empty", "empty");
}
JsonResponse = buffer.toString();
Log.d("response", JsonResponse);
JSONObject jsonObject = new JSONObject(JsonResponse);
JSONArray array = jsonObject.getJSONArray("routes");
JSONObject routes = array.getJSONObject(0);
JSONArray legs = routes.getJSONArray("legs");
JSONObject steps = legs.getJSONObject(0);
JSONObject distance = steps.getJSONObject("distance");
parsedDistance = distance.getString("text");
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
return parsedDistance;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
// Check for the integer request code originally supplied to startResolutionForResult().
case REQUEST_CHECK_SETTINGS:
switch (resultCode) {
case Activity.RESULT_OK:
startLocationUpdates();
break;
case Activity.RESULT_CANCELED:
Intent intent = new Intent(this, Incident.class);
startActivity(intent);
break;
}
break;
}
}
#Override
protected void onStop() {
super.onStop();
if (wakeLock.isHeld()) {
wakeLock.release();
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(this, IncidentView.class);
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
setResult(RESULT_OK, intent);
finish();
}
}
Searched alot and not getting proper way to start with? Any help would really valuable.
--Thanks!
This worked for me:
Capture the latitude and longitude at regular intervals and store. Calculate and sum the distance between each stored value.
I'm developing an app that implement a MapsView. In the MapsView, there're some markers which one of them I clicked, it will showed me the InfoWindow. It works fine if my current location is found. But the problem is when my current location not found (GPS disable), the marker not showed me the InfoWindow when i click it.
Here's my code
//Getting current location
private void getCurrentLocation() {
mMap.clear();
//Creating a location object
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
} else {
Toast.makeText(MapsActivity.this, "Anda harus menyetujuinya agar dapat menggunakan semua fitur yang ada", Toast.LENGTH_LONG).show();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
}
}
if (location != null) {
//Getting longitude and latitude
fromLongitude = location.getLongitude();
fromLatitude = location.getLatitude();
//Creating a LatLng Object to store Coordinates
origin = new LatLng(fromLatitude, fromLongitude);
mo=new MarkerOptions().position(origin).icon(BitmapDescriptorFactory.fromResource(R.mipmap.here));
my_marker=mMap.addMarker(mo);
my_marker.setTitle("I'm Here");
my_marker.setSnippet("Starting point");
my_marker.setDraggable(true);
}
}
class GetInfo extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MapsActivity.this);
dialog.setMessage("Mohon tunggu");
dialog.setTitle("Mendapatkan data...");
dialog.show();
dialog.setCancelable(true);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray konten = jsono.getJSONArray("konten");
mMarkersHashMap = new HashMap<Marker, MyMarker>();
for (int i = 0; i < konten.length(); i++) {
HashMap<String,String> newMap=new HashMap<String,String>();
JSONObject object = konten.getJSONObject(i);
newMap.put("nama", object.getString("nama"));
newMap.put("deskripsi",object.getString("deskripsi"));
newMap.put("foto",object.getString("foto"));
newMap.put("marker", object.getString("marker"));
newMap.put("lat", object.getString("lat"));
newMap.put("lng", object.getString("lng"));
array.add(newMap);
}
return true;
}
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(final Boolean result) {
dialog.cancel();
runOnUiThread(new Runnable() {
#Override
public void run() {
if (!result) {
//Toast.makeText(getApplicationContext(), "Tidak dapat mengambil data dari server, silahkan cek koneksi internet anda", Toast.LENGTH_LONG).show();
showInfo();
}
else {
for (int i = 0; i < array.size(); i++) {
HashMap<String, String> newMap = new HashMap<String, String>();
newMap = array.get(i);
mMyMarkersArray.add(new MyMarker(newMap.get("nama"), newMap.get("deskripsi"), newMap.get("foto"), newMap.get("marker"), Double.parseDouble(newMap.get("lat")), Double.parseDouble(newMap.get("lng"))));
}
plotMarkers(mMyMarkersArray);
}
}
});
}
}
#Override
public void onConnected(Bundle bundle) {
getCurrentLocation();
}
public void plotMarkers(ArrayList<MyMarker> markers) {
if(markers.size() > 0) {
for (MyMarker myMarker : markers)
{
dest = new LatLng(myMarker.getmLatitude(), myMarker.getmLongitude());
markerOption = new MarkerOptions().position(dest);
location_marker = mMap.addMarker(markerOption);
Target target = new PicassoMarker(location_marker);
targets.add(target);
ImageView image = new ImageView(this);
image.setImageResource(R.mipmap.marker);
int width = image.getDrawable().getIntrinsicWidth();
int height = image.getDrawable().getIntrinsicHeight();
Picasso.with(MapsActivity.this).load(myMarker.getmIcon()).resize(width, height).onlyScaleDown().into(target);
mMarkersHashMap.put(location_marker, myMarker);
i = getIntent();
if(i.getBooleanExtra("maps", true)) {
location_marker.setTitle(i.getStringExtra("nama"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(dest, 16));
}
else {
mMap.setInfoWindowAdapter(new MarkerInfoWindowAdapter());
}
}
}
}
public class MarkerInfoWindowAdapter implements GoogleMap.InfoWindowAdapter
{
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
View v = getLayoutInflater().inflate(R.layout.info_windowlayout, null);
MyMarker myMarker = mMarkersHashMap.get(marker);
TextView markerLabel = (TextView) v.findViewById(R.id.marker_label);
markerLabel.setText(myMarker.getmLabel());
ImageView foto = (ImageView) v.findViewById(R.id.foto);
Picasso.with(getApplicationContext()).load(myMarker.getmImage()).placeholder(R.layout.progress).error(R.mipmap.error).into(foto);
TextView anotherLabel = (TextView) v.findViewById(R.id.another_label);
anotherLabel.setText("Baca selengkapnya...");
if (myMarker.getmImage() != null) {
Picasso.with(getApplicationContext())
.load(myMarker.getmImage())
.placeholder(R.layout.progress)
.into(foto, new MarkerCallback(marker));
}
return v;
}
}
public class MarkerCallback implements Callback {
Marker marker=null;
MarkerCallback(Marker marker) {
this.marker=marker;
}
#Override
public void onError() {
Log.e(getClass().getSimpleName(), "Tidak dapat mengambil gambar!");
}
#Override
public void onSuccess() {
if (marker != null && marker.isInfoWindowShown()) {
marker.hideInfoWindow();
marker.showInfoWindow();
}
}
}
Any answer will be greatly appreciated.
Thanks.
I solve the problem by adding this code marker.showInfoWindow(); in onMarkerClick
In my application am plotting the markers from the latitude and longitude from Json when the latitude and longitude is updated in JSON it working fine and the markers get updated.But at sometime the all markers getting disable for a second and enabling.I don't want all the markers to get disable at any time please help me to fix it my code is given below.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_layout_one, container, false);
MapsInitializer.initialize(getActivity());
mMapView = (MapView)rootView.findViewById(R.id.mapView);
mMapView.onCreate(mBundle);
MapsInitializer.initialize(getActivity());
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
/* handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);
Toast.makeText(getActivity(), "Data Updated!!!! ", Toast.LENGTH_SHORT).show();
Log.e("Data in Log", "");
}
}, 1000);
*/
final Handler handler = new Handler();
timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
//mMap.clear();
Toast.makeText(getActivity(), "Data Updated!!!! ", Toast.LENGTH_SHORT).show();
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);
}
});
}
};
timer.schedule(doAsynchronousTask, 20000, 20000);
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);
/*LocationManager locman = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
//locman.requestLocationUpdates(minTime, minDistance, criteria, intent);
locman.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, this);*/
return rootView;
}
private void setUpMapIfNeeded(View inflatedView) {
if (mMap == null) {
mMap = ((MapView) inflatedView.findViewById(R.id.mapView)).getMap();
mMap.setMyLocationEnabled(true);
Location myLocation = mMap.getMyLocation();
if (mMap != null) {
//mMap.clear();
// setUpMap();
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location arg0) {
// TODO Auto-generated method stub
final LatLngBounds.Builder builder = new LatLngBounds.Builder();
mMap.clear();
for (int i = 0; i < arraylist1.size(); i++) {
final LatLng position = new LatLng(Double
.parseDouble(arraylist1.get(i).get("Latitude")),
Double.parseDouble(arraylist1.get(i).get(
"Longitude")));
String ime1 = arraylist1.get(i).get("IME");
final MarkerOptions options = new MarkerOptions()
.position(position);
//mMap.addMarker(options);
//mMap.addMarker(options.icon(BitmapDescriptorFactory .fromResource(R.drawable.buspng)).title(ime1));
marker=mMap.addMarker(new MarkerOptions().position(position).icon(BitmapDescriptorFactory .fromResource(R.drawable.buspng)).title(ime1));
//options.title(ime1);
builder.include(position);
}
LatLng latLng = new LatLng(arg0.getLatitude(), arg0
.getLongitude());
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setMyLocationEnabled(true);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// mMap.setOnMapClickListener(null);
mMap.setOnMarkerClickListener(null);
mMap.animateCamera(CameraUpdateFactory.zoomTo(9));
}
});
}
}
}
/* protected void retrieveAndAddCities() throws IOException {
HttpURLConnection conn = null;
final StringBuilder json = new StringBuilder();
try {
URL url = new URL(SERVICE_URL);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
json.append(buff, 0, read);
}
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to service", e);
throw new IOException("Error connecting to service", e);
} finally {
if (conn != null) {
conn.disconnect();
}
}
new DownloadJSON().execute();
} */
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
String result="";
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {
arraylist1 = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
String result = "";
json = jParser.getJSONFromUrl(SERVICE_URL);
try {
//arraylist1.clear();
jsonarray = json.getJSONArray("SingleIMEs");
Log.d("Haaaaaaaaaaaa", "" + json);
for (int i = 0; i < jsonarray.length(); i++) {
Log.d("H11111111111111111111111111",
"" + jsonarray.length());
map = new HashMap<String, String>();
json = jsonarray.getJSONObject(i);
latitude = json.getDouble("Latitude");
longitude = json.getDouble("Longitude");
ime = json.getString("IME");
map.put("Latitude", json.getString("Latitude"));
Log.e("CHECKLAT",""+json.getString("Latitude") );
map.put("Longitude", json.getString("Longitude"));
Log.e("CHECKLONG",""+json.getString("Longitude") );
map.put("IME", json.getString("IME"));
arraylist1.add(map);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
result="Error";
e.printStackTrace();
}
}catch(Exception e){
result="Error";
}
return null;
}
protected void onPostExecute(Void args) {
// mProgressDialog.dismiss();
}
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
/* Toast.makeText(getActivity(), "onLocationUpdated!!!", Toast.LENGTH_SHORT).show();
Log.d("onLocationUpdated!!!","");
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);*/
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
}
I think it is some memory issue...
Try to override this method...
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
In this for loo you are refrencing to same marker variable:
marker=mMap.addMarker(new MarkerOptions().position(position).icon(BitmapDescriptorFactory .fromResource(R.drawable.buspng)).title(ime1));
for (int i = 0; i < arraylist1.size(); i++) {
final LatLng position = new LatLng(Double
.parseDouble(arraylist1.get(i).get("Latitude")),
Double.parseDouble(arraylist1.get(i).get(
"Longitude")));
String ime1 = arraylist1.get(i).get("IME");
final MarkerOptions options = new MarkerOptions()
.position(position);
//mMap.addMarker(options);
//mMap.addMarker(options.icon(BitmapDescriptorFactory .fromResource(R.drawable.buspng)).title(ime1));
marker=mMap.addMarker(new MarkerOptions().position(position).icon(BitmapDescriptorFactory .fromResource(R.drawable.buspng)).title(ime1));
//options.title(ime1);
builder.include(position);
}
So just remove marker = and make it
> mMap.addMarker(new MarkerOptions().position(position).icon(BitmapDescriptorFactory
> .fromResource(R.drawable.buspng)).title(ime1));
Hope this will work
here i want to show detail onclick of marker into infowindow according to its latlong and want to do new event onclick infowindow. here i made a markerlist and lat1 long1 array which is taking from url and you can see private void setUpMapIfNeeded() this function
Here nameb is containing marker names list
public class Mainactivity extends FragmentActivity {
String friendid;
Double lng1;
Double lat1;
String lat;
String lon;
String gen;
String test;
String gender;
String result;
Drawable drawable;
String frid;
String nameb;
private GoogleMap mMap;
ImageView logout;
private static final int DIALOG_ALERT = 10;
Bitmap bm;
static boolean Iscamera=false;
ArrayList<Double> arrayLat = null;
ArrayList<Double> arrayLong = null;
ArrayList<String> arrayGender = null;
ArrayList<String> arrayUsername = null;
ArrayList<String> arrayFrnd = null;
static ArrayList<Marker> markerList = null;
EventListTask eventListTask;
TextView tvLng;
TextView tvLat;
private static final int NOTIFICATION_ID = 1;
private AQuery androidAQuery;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.flirtalerthome_screen);
logout = (ImageView) findViewById(R.id.logoutimage);
//*************************************************************************************************************
androidAQuery=new AQuery(this);
androidAQuery.ajax(Constant.Profile_Image, Bitmap.class, 0,new AjaxCallback<Bitmap>(){
#Override
public void callback(String url, Bitmap object, com.androidquery.callback.AjaxStatus status) {
super.callback(url, object, status);
bm=object;
//You will get Bitmap from object.
}
});
// ***************************************************************************************************************
new EventListTask().execute();
logout.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDialog(DIALOG_ALERT);
}
});
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
new EventListTask().execute();
}
private void setUpMapIfNeeded() {
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
mMap.setMyLocationEnabled(true);
if (mMap != null) {
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location arg0) {
// TODO Auto-generated method stub
mMap.clear();
if(!Iscamera){
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(arg0.getLatitude(), arg0
.getLongitude()), 20));
Iscamera = true;
}
try{
mMap.setInfoWindowAdapter(new InfoWindowAdapter()
{
// Use default InfoWindow frame
public View getInfoWindow(Marker marker) {
return null;
}
// Defines the contents of the InfoWindow
public View getInfoContents(Marker marker) {
// Getting view from the layout file info_window_layout
View v = getLayoutInflater().inflate(R.layout.info_window_layout, null);
// Getting the position from the marker
//
// Getting reference to the TextView to set latitude
tvLat = (TextView) v.findViewById(R.id.tv_lat);
// Getting reference to the TextView to set longitude
// TextView tv = (TextView) v.findViewById(R.id.tv);
// Setting the latitude
// tvLat.setText();
// Setting the longitude
// tvLng.setText(nameb);
// Returning the view containing InfoWindow contents
return v;
}
});
for (int i = 0; i < arrayLat.size(); i++) {
lat1 = arrayLat.get(i);
lng1 = arrayLong.get(i);
gen = arrayGender.get(i);
frid = arrayFrnd.get(i);
nameb = arrayUsername.get(i);
if (gen.equals("1")) {
markerList
.add(mMap.addMarker(new MarkerOptions()
.position(new LatLng(lat1, lng1))
.title(nameb)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.bluesmilelarge))));
} else if (gen.equals("2")) {
markerList
.add(mMap.addMarker(new MarkerOptions()
.position(new LatLng(lat1, lng1))
.title(nameb)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.purplesmilelarge))));
} else {
markerList
.add(mMap.addMarker(new MarkerOptions()
.position(new LatLng(lat1, lng1))
.title(nameb)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.purplesmilelarge))));
}
}
mMap.addMarker(new MarkerOptions()
.position(
new LatLng(arg0.getLatitude(), arg0
.getLongitude()))
.title(Constant.USERNAME)
.icon(BitmapDescriptorFactory.fromBitmap(bm)));
}catch (Exception e){
Toast.makeText(getApplicationContext(),
e.getMessage(),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(),
e.getMessage(), e);
}
}
});
}
}
}
#SuppressWarnings("unused")
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title(
"Marker"));
}
// ***********************************************************************************************************************
#SuppressWarnings("deprecation")
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_ALERT:
// Create out AlterDialog
Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure,want to logout");
builder.setCancelable(true);
builder.setPositiveButton("Yes", new OkOnClickListener());
builder.setNegativeButton("No", new CancelOnClickListener());
AlertDialog dialog = builder.create();
dialog.show();
}
return super.onCreateDialog(id);
}
private final class CancelOnClickListener implements
DialogInterface.OnClickListener {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}
private final class OkOnClickListener implements
DialogInterface.OnClickListener {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(FlirtHome_Screen.this, LoginScreen.class);
SharedPreferences settings = getSharedPreferences(
Constant.PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("logged", null);
editor.commit();
startActivity(intent);
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
System.exit(0);
}
}
// ********************************************************************************************************************
private class EventListTask extends AsyncTask<Context, Void, Void> {
ProgressDialog dialog = new ProgressDialog(FlirtHome_Screen.this);
String message;
String s;
protected void onPreExecute() {
super.onPreExecute();
dialog.setMessage("Loading....please wait ");
dialog.setCancelable(false);
dialog.show();
}
protected Void doInBackground(Context... params) {
try {
message = myMethod();
s = saveData(message);
// bm = drawableToBitmap(draw);
} catch (Exception e) {
System.out.print(e.getMessage());
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (s == null) {
} else {
for (int i = 0; i < arrayLat.size(); i++) {
lat1 = arrayLat.get(i);
lng1 = arrayLong.get(i);
gen = arrayGender.get(i);
frid = arrayFrnd.get(i);
nameb = arrayUsername.get(i);
if (gen.equals("1")) {
markerList
.add(mMap.addMarker(new MarkerOptions()
.position(new LatLng(lat1, lng1))
.title(nameb)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.bluesmilelarge))));
} else if (gen.equals("2")) {
markerList
.add(mMap.addMarker(new MarkerOptions()
.position(new LatLng(lat1, lng1))
.title(nameb)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.purplesmilelarge))));
} else {
markerList
.add(mMap.addMarker(new MarkerOptions()
.position(new LatLng(lat1, lng1))
.title(nameb)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.purplesmilelarge))));
}
}
}
dialog.dismiss();
}
}
public String myMethod() throws IOException, JSONException {
String url1 = "url";
System.out.println("In get Category method" + url1);
URL url = new URL(url1);
URLConnection urlcon = url.openConnection();
String jsonresponse = convertStreamToString(urlcon.getInputStream());
Log.e("response", jsonresponse);
return jsonresponse;
}
public String convertStreamToString(InputStream is) {
if (is != null) {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is,
"UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return writer.toString();
} else {
return "";
}
}
private String saveData(String result) {
try {
arrayLat = new ArrayList<Double>();
arrayLong = new ArrayList<Double>();
arrayGender = new ArrayList<String>();
arrayUsername = new ArrayList<String>();
arrayFrnd = new ArrayList<String>();
markerList = new ArrayList<Marker>();
JSONObject json = (JSONObject) new JSONTokener(result).nextValue();
JSONObject json2 = json.getJSONObject("response");
JSONArray jsonArray = json2.getJSONArray("incircle");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject objJson = jsonArray.getJSONObject(i);
test = objJson.getString("username");
arrayUsername.add(test);
friendid = objJson.getString("useid");
arrayFrnd.add(friendid);
Constant.FRIENDIDLIST.add(friendid);
lat = objJson.getString("lat");
Constant.LATITUDEFLIST.add(lat);
arrayLat.add(Double.parseDouble(lat));
lon = objJson.getString("log");
Constant.LONGITUDEFLIST.add(lon);
arrayLong.add(Double.parseDouble(lon));
gender = objJson.getString("gender");
arrayGender.add(gender);
}
} catch (JSONException e) {
e.printStackTrace();
}
return test;
}
public void onBackPressed() {
return;
}
}
For showing different items in infowindow you need to use infowindowadapter.
Here is sample code.You can take reference from here.
private GoogleMap googleMap;
private double[][] arrayLatLng = new double[][] { { 21.943046, 72.088989 }, { 26.843677, 73.407349 }, { 30.315988, 77.076782 }, { 29.05617, 82.042603 }, { 25.819672, 85.90979 },
{ 24.726875, 89.667114 }, { 22.87744, 86.766724 }, { 18.937464, 82.723755 }, { 15.411319, 79.603638 }, { 12.618897, 77.670044 }, { 15.771109, 74.747681 }, { 20.055931, 73.780884 } };
private String[] locationName = new String[] { "Bhavnagar, Gujarat", "Rajasthan", "Chandigarth", "Nepal", "Bihar", "Bangladesh", "West Bengal", "Orissa", "Andhra Pradesh", "Karnataka",
"Bail Hongal, Maharastra", "Nasik, Maharastra" };
private MarkerInfoWindowAdapter infoWindowAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
googleMap.setOnMarkerClickListener(this);
googleMap.setOnInfoWindowClickListener(this);
googleMap.getUiSettings().setAllGesturesEnabled(true);
// infoWindowAdapter = new MarkerInfoWindowAdapter();
googleMap.setInfoWindowAdapter(infoWindowAdapter);
final PolygonOptions polygonOptions = new PolygonOptions();
polygonOptions.strokeColor(Color.BLUE);
polygonOptions.strokeWidth(3);
// polygonOptions.fillColor(Color.RED);
for (int i = 0; i < arrayLatLng.length; i++) {
final LatLng latLng = new LatLng(arrayLatLng[i][0], arrayLatLng[i][1]);
polygonOptions.add(latLng);
googleMap.addMarker(new MarkerOptions().position(latLng).title(locationName[i]).snippet(arrayLatLng[i][0] + ", " + arrayLatLng[i][1])
.icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker)));
infoWindowAdapter = new MarkerInfoWindowAdapter();
infoWindowAdapter.setTitle(locationName[i]);
infoWindowAdapter.setDescription(locationName[i]);
}
googleMap.addPolygon(polygonOptions);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(arrayLatLng[0][0], arrayLatLng[0][1]), 4));
}
#Override
public boolean onMarkerClick(Marker marker) {
Log.e("Marker Click", "Click Found");
// marker.showInfoWindow();
return false;
}
#Override
public void onInfoWindowClick(Marker marker) {
if (marker.isInfoWindowShown()) {
marker.hideInfoWindow();
}
}
class MarkerInfoWindowAdapter implements InfoWindowAdapter {
private View inflatedView;
private View tempView;
private String title, description;
public void setTitle(String title) {
this.title = title;
}
public void setDescription(String description) {
this.description = description;
}
MarkerInfoWindowAdapter() {
inflatedView = getLayoutInflater().inflate(R.layout.location_info_window, null);
tempView = getLayoutInflater().inflate(R.layout.location_content_window, null);
}
#Override
public View getInfoContents(Marker marker) {
setInfo(marker, inflatedView);
return inflatedView;
}
#Override
public View getInfoWindow(Marker marker) {
setInfo(marker, inflatedView);
return inflatedView;
}
private void setInfo(Marker marker, View view) {
final TextView txtTitle = (TextView) view.findViewById(R.id.txtTitle);
final TextView txtDescription = (TextView) view.findViewById(R.id.txtDescription);
txtTitle.setText(title);
txtDescription.setText(description);
}
}