I'm doing an app that show some POI on the map after reading a json with this points.
my app work well in android 4.4 but when I run it in android 6 (both emulator and real device), the camera does not zoom at the level I'm setting.
I'm receiving no errors or warning about some deprecated command.
this is the code in the MainActivity
#Override
public void onMapReady(GoogleMap map) {
mapVar = map;
// MapWrapperLayout initialization
final MapWrapperLayout mapWrapperLayout = (MapWrapperLayout) findViewById(R.id.map_relative_layout);
// MapWrapperLayout initialization
mapWrapperLayout.init(map, getPixelsFromDp(this, 39 + 20));
this.infoWindow = (ViewGroup) getLayoutInflater().inflate(R.layout.info_window, null);
this.infoTitle = (TextView) infoWindow.findViewById(R.id.title);
this.infoSnippet = (TextView) infoWindow.findViewById(R.id.snippet);
this.infoButton = (Button) infoWindow.findViewById(R.id.button);
// Setting custom OnTouchListener which deals with the pressed state
// so it shows up
this.infoButtonListener = new OnInfoWindowElemTouchListener(infoButton,
getResources().getDrawable(R.drawable.round_but_green_sel), //btn_default_normal_holo_light
getResources().getDrawable(R.drawable.round_but_red_sel)) //btn_default_pressed_holo_light
{
#Override
protected void onClickConfirmed(View v, Marker marker) {
// Here we can perform some action triggered after clicking the button
//Toast.makeText(MainActivity.this, marker.getTitle() + "'s button clicked!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, dettaglio.class);
//EditText editText = (EditText) findViewById(R.id.edit_message);
String titolo = marker.getTitle();
String idPOI = allMarkersMapIds.get(marker);
String IMGPOI = allMarkersMapImg.get(marker);
String Desc = allMarkersMapDesc.get(marker);
String idUtentePOI = allMarkersMapidUtente.get(marker);
String idCategoria = allMarkersMapidCategoria.get(marker);
LATLON = marker.getPosition();
Bundle args = new Bundle();
args.putParcelable("coordinatePOI", LATLON);
intent.putExtra("bundle", args);
intent.putExtra(EXTRA_MESSAGE, titolo);
intent.putExtra(EXTRA_ID, idPOI);
intent.putExtra(EXTRA_IMG, IMGPOI);
intent.putExtra(EXTRA_Desc, Desc);
intent.putExtra("IDCATEGORIAPOI", idCategoria);
intent.putExtra("IDUTENTEPOI", idUtentePOI);
startActivity(intent);
}
};
this.infoButton.setOnTouchListener(infoButtonListener);
map.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
// Setting up the infoWindow with current's marker info
infoTitle.setText(marker.getTitle());
infoSnippet.setText(marker.getSnippet());
infoButtonListener.setMarker(marker);
// We must call this to set the current marker and infoWindow references
// to the MapWrapperLayout
mapWrapperLayout.setMarkerWithInfoWindow(marker, infoWindow);
return infoWindow;
}
});
/// HERE I CENTER AND ZOOM THE CAMERA
CameraPosition googlePlex = CameraPosition.builder()
.target(new LatLng(latitude, longitude))
.zoom(15)
.bearing(0)
.tilt(45)
.build();
setUpMapIfNeeded(0, ricercaString);
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
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
map.setMyLocationEnabled(true);
map.moveCamera(CameraUpdateFactory.newCameraPosition(googlePlex));
map.animateCamera(CameraUpdateFactory.newCameraPosition(googlePlex), 2000, null);
}
and I'm doing the same thing inside a service that listen for location changes
#Override
public void onLocationChanged(Location location) {
listPOI = MainActivity.getArrayList();
// a bool value to understand if I can go ahead
goAhead = MainActivity.getGoAhead();
namesPOI = MainActivity.getNamePOI();
range = PrefActivity.getRange();
proximity = PrefActivity.getProximity();
//checks whether the user wants to be notified
if(proximity) {
//check if the list of near POI is loaded
if (goAhead) {
if (utility.isNear(location, listPOI, namesPOI, range)) {
POI = utility.getNamePOI();
String msg = "You're near " + POI;
tts1.tts.speak(msg, TextToSpeech.QUEUE_FLUSH, null);
}
}
}
getLocation();
CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(),location.getLongitude()));
MainActivity.mapVar.moveCamera(center);
CameraUpdate zoom = CameraUpdateFactory.zoomTo(15);
MainActivity.mapVar.animateCamera(zoom);
}
But the zoom is still at world level...somebody can figure out why?
Ok, I changed the onMapReady as follows, and now it work.
#Override
public void onMapReady(GoogleMap map) {
mapVar = map;
// MapWrapperLayout initialization
CameraPosition googlePlex = CameraPosition.builder()
.target(new LatLng(latitude, longitude))
.zoom(15)
.bearing(0)
.tilt(45)
.build();
map.animateCamera(CameraUpdateFactory.newCameraPosition(googlePlex), 2000, null);
final MapWrapperLayout mapWrapperLayout = (MapWrapperLayout) findViewById(R.id.map_relative_layout);
// MapWrapperLayout initialization
mapWrapperLayout.init(map, getPixelsFromDp(this, 39 + 20));
this.infoWindow = (ViewGroup) getLayoutInflater().inflate(R.layout.info_window, null);
this.infoTitle = (TextView) infoWindow.findViewById(R.id.title);
this.infoSnippet = (TextView) infoWindow.findViewById(R.id.snippet);
this.infoButton = (Button) infoWindow.findViewById(R.id.button);
// Setting custom OnTouchListener which deals with the pressed state
// so it shows up
this.infoButtonListener = new OnInfoWindowElemTouchListener(infoButton,
getResources().getDrawable(R.drawable.round_but_green_sel), //btn_default_normal_holo_light
getResources().getDrawable(R.drawable.round_but_red_sel)) //btn_default_pressed_holo_light
{
#Override
protected void onClickConfirmed(View v, Marker marker) {
// Here we can perform some action triggered after clicking the button
//Toast.makeText(MainActivity.this, marker.getTitle() + "'s button clicked!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, dettaglio.class);
//EditText editText = (EditText) findViewById(R.id.edit_message);
String titolo = marker.getTitle();
String idPOI = allMarkersMapIds.get(marker);
String IMGPOI = allMarkersMapImg.get(marker);
String Desc = allMarkersMapDesc.get(marker);
String idUtentePOI = allMarkersMapidUtente.get(marker);
String idCategoria = allMarkersMapidCategoria.get(marker);
LATLON = marker.getPosition();
Bundle args = new Bundle();
args.putParcelable("coordinatePOI", LATLON);
intent.putExtra("bundle", args);
intent.putExtra(EXTRA_MESSAGE, titolo);
intent.putExtra(EXTRA_ID, idPOI);
intent.putExtra(EXTRA_IMG, IMGPOI);
intent.putExtra(EXTRA_Desc, Desc);
intent.putExtra("IDCATEGORIAPOI", idCategoria);
intent.putExtra("IDUTENTEPOI", idUtentePOI);
startActivity(intent);
}
};
this.infoButton.setOnTouchListener(infoButtonListener);
map.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
// Setting up the infoWindow with current's marker info
infoTitle.setText(marker.getTitle());
infoSnippet.setText(marker.getSnippet());
infoButtonListener.setMarker(marker);
// We must call this to set the current marker and infoWindow references
// to the MapWrapperLayout
mapWrapperLayout.setMarkerWithInfoWindow(marker, infoWindow);
return infoWindow;
}
});
setUpMapIfNeeded(0, ricercaString);
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
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
map.setMyLocationEnabled(true);
}
1.
Instead of animateCamera > newCameraPosition use moveCamera > newLatLngZoom
Replace
CameraPosition cameraPosition = new CameraPosition.Builder().target(location).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
with
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location, 9));
Use CancelableCallback in animateCamera (kind of work around)
.
googleMap.animateCamera(CameraUpdateFactory.newLatLngBounds(latLngBounds, 5), new GoogleMap.CancelableCallback() {
#Override
public void onFinish() {
CameraUpdate zout = CameraUpdateFactory.zoomBy(-3f);
googleMap.animateCamera(zout);
}
#Override
public void onCancel() {
}
});
Related
i've a big probleme for 4 months now, and i don't know what's the solution. When i'm launching my application, the app demand to the user if he want to activate the loalisation (its important), if he say "no", then nothing happen but the app will ask him later, and if he say "yes", then the app will open setting location of the app, and the user need to press "activate location" on phone setting.
The probleme is, after activating location (it doesn't show the userLocation bc i don't know how to do this and its not my first priority), when you click on the geolocalisationButton , you need to press 3 time the button for showing user his location (sometime 2, or 4 times, it's depend, i don't know why).
This is the video for the exemple --> video
onCreate Code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout_map_priere);
supportMapFragment = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.google_map);
//location
client = LocationServices.getFusedLocationProviderClient(layout_map_priere.this);
//check Permissions
if (ActivityCompat.checkSelfPermission(layout_map_priere.this,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(layout_map_priere.this,
Manifest.permission.ACCESS_COARSE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
//When both permission granted
//Call method
getCurrentLocation();
}else {
//When permissions denied
//Request permission
ActivityCompat.requestPermissions(layout_map_priere.this, new String[]{
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION
}, 100);
}
trackButton();
}
My Customize Geolocalisation Button
private void geoButton() {
locationButton = (View) supportMapFragment.getView().findViewById(Integer.parseInt("1")).getParent();
locationButton = supportMapFragment.getView().findViewById(Integer.parseInt("2"));
locationButton.setVisibility(View.GONE);
}
onClickable Geolocalisation Button
private void trackButton() {
final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
ImageButton camera_track = (ImageButton) findViewById(R.id.back_to_camera_tracking_mode);
geoButton();
camera_track.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER) &&
manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
getCurrentLocation();
}else {
buildAlertMessageNoGps();
}
}
});
}
Getting The User Location
#SuppressLint("MissingPermission")
private void getCurrentLocation() {
//Initialize task Location
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//check Condition
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
//When Location service is enabled
//Get Last Location
client.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
#Override
public void onComplete(#NonNull Task<Location> task) {
Location location = task.getResult();
//Check condition
if (location != null){
//Sync map
supportMapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap map) {
//initialize Lat Lng
LatLng myposition = new LatLng(location.getLatitude(), location.getLongitude());
map.animateCamera(CameraUpdateFactory.newLatLngZoom(myposition, 12));
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (ActivityCompat.checkSelfPermission(layout_map_priere.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(layout_map_priere.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
map.setMyLocationEnabled(true);
locationButton = (View) supportMapFragment.getView().findViewById(Integer.parseInt("1")).getParent();
locationButton = supportMapFragment.getView().findViewById(Integer.parseInt("2"));
locationButton.setVisibility(View.GONE);
View toolbar = ((View) supportMapFragment.getView().findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("4"));
RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams) toolbar.getLayoutParams();
rlp.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
rlp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 0);
rlp.addRule(RelativeLayout.ALIGN_PARENT_LEFT, 0);
rlp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
rlp.setMargins(0, 0, 30, 30);
map.getUiSettings().setCompassEnabled(false);
map.getUiSettings().setMapToolbarEnabled(false);
map.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
final LinearLayout layout_scroll = (LinearLayout) findViewById(R.id.layout_scroll);
final ViewGroup.LayoutParams params = layout_scroll.getLayoutParams();
layout_scroll.setVisibility(View.INVISIBLE);
params.height = 0;
layout_scroll.setLayoutParams(params);
final LinearLayout layout_more_block = (LinearLayout) findViewById(R.id.layout_more_block);
final ViewGroup.LayoutParams params_more = layout_more_block.getLayoutParams();
layout_more_block.setVisibility(View.INVISIBLE);
params_more.height = 0;
layout_more_block.setLayoutParams(params_more);
Animation slideDown = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_down);
layout_more_block.startAnimation(slideDown);
}
});
}
});
}else {
LocationRequest locationRequest = new LocationRequest()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10000)
.setFastestInterval(1000)
.setNumUpdates(1);
//Initialize location call back
LocationCallback locationCallback = new LocationCallback(){
#Override
public void onLocationResult(LocationResult locationResult) {
//initalize location
Location location1 = locationResult.getLastLocation();
}
};
//Request location updates
client.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
}
}
});
}else {
buildAlertMessageNoGps();
}
}
Finnaly, My Builded Alert Message If No Gps
private void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Votre GPS semble être désactivé. Voulez-vous l'activer ?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
I really need your help, why i have this problem, and how can i fix it
I am using googleAPIClient to get the current lat long values using Location. I am getting the values of both my current lat and long in a separate class. I need to pass these current lat and long values inside my MapsActivity ( GoogleMap Activity), Since I have already created the object for the another class, from which I need to get the values, I don't know how to pass the values to this activity from the class.
Here's what I have tried. This is the class which I have created to get the current lat long values:
CurrentValues.java:
public class CurrentValues implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private static final String TAG = CurrentValues.class.getSimpleName();
private Context context;
private GoogleApiClient mGoogleApiClient;
private Location mLocation;
private LocationManager mLocationManager;
private LocationRequest mLocationRequest;
private long UPDATE_INTERVAL = 2 * 1000; /* 10 secs */
private long FASTEST_INTERVAL = 2000; /* 2 sec */
public CurrentValues( Context context){
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
checkLocation();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
startLocationUpdates();
mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLocation == null){
startLocationUpdates();
}
if (mLocation != null) {
// mLatitudeTextView.setText(String.valueOf(mLocation.getLatitude()));
//mLongitudeTextView.setText(String.valueOf(mLocation.getLongitude()));
} else {
Toast.makeText(context, "Location not Detected", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Connection Suspended");
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.i(TAG, "Connection failed. Error: " + connectionResult.getErrorCode());
}
#Override
public void onLocationChanged(Location location) {
String msg = "Updated Location: " +
Double.toString(location.getLatitude()) + "," +
Double.toString(location.getLongitude());
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
}
private boolean checkLocation() {
if(!isLocationEnabled())
showAlert();
return isLocationEnabled();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
private boolean isLocationEnabled() {
mLocationManager = (LocationManager)context. getSystemService(Context.LOCATION_SERVICE);
return mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
private void showAlert() {
final AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setTitle("Enable Location")
.setMessage("Your Locations Settings is set to 'Off'.\nPlease Enable Location to " +
"use this app")
.setPositiveButton("Location Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(myIntent);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
}
});
dialog.show();
}
protected void startLocationUpdates() {
// Create the location request
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(UPDATE_INTERVAL)
.setFastestInterval(FASTEST_INTERVAL);
// Request location updates
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, (com.google.android.gms.location.LocationListener) context);
Log.d("reque", "--->>>>");
}
}
Now I need to pass the lat long values I got from this class to MapsActivity. Since I had already created object for the currentvalues class here in this activity, I don't know how to pass the value from there to here.
Here's my MapActivity (GoogleMap Activity)
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private CurrentValues currentValues;
private Location location;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// // Add a marker in Sydney and move the camera
// LatLng sydney = new LatLng(-34, 151);
// mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
//
// LatLng chennai = new LatLng(13.06,80);
// mMap.addMarker(new MarkerOptions().position(chennai).title("Marker in Chennai"));
LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
googleMap.addMarker(new MarkerOptions().position(latLng));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 8f));
// creating object for currentValues class
CurrentValues currentValues = new CurrentValues(this);
}
}
I don't know how to proceed after this to pass the lat long values here. How can I proceed?
I am trying to change the position of my location button in my Maps Android App from top to bottom. Seems like it is default in top. Please help me changing the position of it. I have taken the code from the google samples github. This is the new version of code which uses getMapAsync instead of getMap.
MapsActivity.java:
public class MapsActivity extends AppCompatActivity implements GoogleMap.OnMyLocationButtonClickListener,
GoogleMap.OnMyLocationClickListener,
OnMapReadyCallback,
ActivityCompat.OnRequestPermissionsResultCallback {
/**
* Request code for location permission request.
*
* #see #onRequestPermissionsResult(int, String[], int[])
*/
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
/**
* Flag indicating whether a requested permission has been denied after returning in
* {#link #onRequestPermissionsResult(int, String[], int[])}.
*/
private boolean mPermissionDenied = false;
private GoogleMap mMap;
private PlaceAutocompleteFragment placeAutocompleteFragment;
Marker marker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
placeAutocompleteFragment = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
// placeAutocompleteFragment.setFilter(new AutocompleteFilter.Builder().setCountry("ID").build());
placeAutocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
final LatLng latLngLoc = place.getLatLng();
if (marker != null) {
marker.remove();
}
marker = mMap.addMarker(new MarkerOptions().position(latLngLoc).title(place.getName().toString()));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLngLoc));
mMap.animateCamera(CameraUpdateFactory.zoomTo(12), 2000, null);
}
#Override
public void onError(Status status) {
Toast.makeText(MapsActivity.this, "" + status.toString(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnMyLocationButtonClickListener(this);
mMap.setOnMyLocationClickListener(this);
enableMyLocation();
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Setting the position for the marker
markerOptions.position(point);
// changing the marker title
double lat = point.latitude;
double lng = point.longitude;
Geocoder gc = new Geocoder(MapsActivity.this);
List<Address> list = null;
try {
list = gc.getFromLocation(lat, lng, 1);
} catch (IOException e) {
e.printStackTrace();
}
Address address = list.get(0);
String sublocality = address.getSubLocality();
// Setting the title for the marker.
// This will be displayed on taping the marker
markerOptions.title(sublocality);
// Clears the previously touched position
mMap.clear();
// Animating to the touched position
mMap.animateCamera(CameraUpdateFactory.newLatLng(point));
// Placing a marker on the touched position
mMap.addMarker(markerOptions);
}
});
}
private void enableMyLocation() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Permission to access the location is missing.
PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE,
Manifest.permission.ACCESS_FINE_LOCATION, true);
} else if (mMap != null) {
// Access to the location has been granted to the app.
mMap.setMyLocationEnabled(true);
}
}
#Override
public boolean onMyLocationButtonClick() {
Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
// Return false so that we don't consume the event and the default behavior still occurs
// (the camera animates to the user's current position).
return false;
}
#Override
public void onMyLocationClick(#NonNull Location location) {
Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG).show();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) {
return;
}
if (PermissionUtils.isPermissionGranted(permissions, grantResults,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Enable the my location layer if the permission has been granted.
enableMyLocation();
} else {
// Display the missing permission error dialog when the fragments resume.
mPermissionDenied = true;
}
}
#Override
protected void onResumeFragments() {
super.onResumeFragments();
if (mPermissionDenied) {
// Permission was not granted, display error dialog.
showMissingPermissionError();
mPermissionDenied = false;
}
}
/**
* Displays a dialog with error message explaining that the location permission is missing.
*/
private void showMissingPermissionError() {
PermissionUtils.PermissionDeniedDialog
.newInstance(true).show(getSupportFragmentManager(), "dialog");
}
}
Guys, I have resolved it.
Add the following lines in your on create below SupportMapFragent.
View myLocationButton = mapFragment.getView().findViewById(0x2);
if (myLocationButton != null && myLocationButton.getLayoutParams() instanceof RelativeLayout.LayoutParams) {
// location button is inside of RelativeLayout
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) myLocationButton.getLayoutParams();
// Align it to - parent BOTTOM|LEFT
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 0);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
// Update margins, set to 80dp
final int margin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 80,
getResources().getDisplayMetrics());
params.setMargins(margin, margin, margin, margin);
myLocationButton.setLayoutParams(params);
}
Which methods do I have to include to my code to pass the data to list view?
I want to show the nearby places using ListView. It only show the nearby places on the map by clicking the buttons as shown below. When I click the "Nearby School" button it displays the nearby school on the map, now I want it to display the nearby schools using listview. How can I do that?
public class MapsActivity extends FragmentActivity implements com.google.android.gms.location.LocationListener, OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private GoogleMap mMap;
double latitude;
double longitude;
private int PROXIMITY_RADIUS = 10000;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
ListView lvMap;
ArrayList<HashMap<String, String>> placesListItems = new ArrayList<HashMap<String,String>>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
//Check if Google Play Services Available or not
if (!CheckGooglePlayServices()) {
Log.d("onCreate", "Finishing test case since Google Play Services are not available");
finish();
}
else {
Log.d("onCreate","Google Play Services available.");
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.maps);
mapFragment.getMapAsync(this);
}
private boolean CheckGooglePlayServices() {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result = googleAPI.isGooglePlayServicesAvailable(this);
if(result != ConnectionResult.SUCCESS) {
if(googleAPI.isUserResolvableError(result)) {
googleAPI.getErrorDialog(this, result,
0).show();
}
return false;
}
return true;
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
Button btnRestaurant = (Button) findViewById(R.id.btnRestaurant);
btnRestaurant.setOnClickListener(new View.OnClickListener() {
String Restaurant = "restaurant";
#Override
public void onClick(View v) {
Log.d("onClick", "Button is Clicked");
mMap.clear();
String url = getUrl(latitude, longitude, Restaurant);
Object[] DataTransfer = new Object[2];
DataTransfer[0] = mMap;
DataTransfer[1] = url;
Log.d("onClick", url);
GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
getNearbyPlacesData.execute(DataTransfer);
Toast.makeText(MapsActivity.this,"Nearby Restaurants", Toast.LENGTH_LONG).show();
}
});
Button btnHospital = (Button) findViewById(R.id.btnHospital);
btnHospital.setOnClickListener(new View.OnClickListener() {
String Hospital = "hospital";
#Override
public void onClick(View v) {
Log.d("onClick", "Button is Clicked");
mMap.clear();
String url = getUrl(latitude, longitude, Hospital);
Object[] DataTransfer = new Object[2];
DataTransfer[0] = mMap;
DataTransfer[1] = url;
Log.d("onClick", url);
GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
getNearbyPlacesData.execute(DataTransfer);
Toast.makeText(MapsActivity.this,"Nearby Hospitals", Toast.LENGTH_LONG).show();
}
});
Button btnSchool = (Button) findViewById(R.id.btnSchool);
btnSchool.setOnClickListener(new View.OnClickListener() {
String School = "school";
#Override
public void onClick(View v) {
Log.d("onClick", "Button is Clicked");
mMap.clear();
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
String url = getUrl(latitude, longitude, School);
Object[] DataTransfer = new Object[2];
DataTransfer[0] = mMap;
DataTransfer[1] = url;
Log.d("onClick", url);
GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
getNearbyPlacesData.execute(DataTransfer);
Toast.makeText(MapsActivity.this,"Nearby Schools", Toast.LENGTH_LONG).show();
}
});
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
private String getUrl(double latitude, double longitude, String nearbyPlace) {
StringBuilder googlePlacesUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
googlePlacesUrl.append("location=" + latitude + "," + longitude);
googlePlacesUrl.append("&radius=" + PROXIMITY_RADIUS);
googlePlacesUrl.append("&type=" + nearbyPlace);
googlePlacesUrl.append("&sensor=true");
googlePlacesUrl.append("&key=" + "AIzaSyATuUiZUkEc_UgHuqsBJa1oqaODI-3mLs0");
Log.d("getUrl", googlePlacesUrl.toString());
return (googlePlacesUrl.toString());
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
Log.d("onLocationChanged", "entered");
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
Toast.makeText(MapsActivity.this,"Your Current Location", Toast.LENGTH_LONG).show();
Log.d("onLocationChanged", String.format("latitude:%.3f longitude:%.3f",latitude,longitude));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
Log.d("onLocationChanged", "Removing Location Updates");
}
Log.d("onLocationChanged", "Exit");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
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.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#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. Do the
// contacts-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
// Permission denied, 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.
// You can add here other case statements according to your requirement.
}
}
}
I am connecting my app to a sensor, everytime the sensor sends data a marker is placed on a map with data inside info window.
When I am starting the activity the first time. mMap has ID: 21319.
In my onLocationChanged()method I add markers to the map with ID 21319. Then if I press the back button and resume the activity. mMap is created again and has now another ID, let's say ID 22431. With my method addMapPoints() I add the old markers to mMap with ID 22431 with mMap.addMarker(markerOptions) and I can see the markers on the screen. But this time when new data is sent and markers are added inside onLocationChanged() no new markers appear on the screen. When I debug I can see that in onLocationChanged() my mMap has the old ID: 21319 and I do not get any errors. So I guess that the new markers are added to the old map but my screen is showing the new map.
Why is this happening? And how can I solve this problem?
UPDATE I think I have found the problem. At the moment mMap == null when new data is sent. What I now wonder is how can I obtain the map inside OnLocationUpdate() or in OnResume()?
Here is my MapsActivity code
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener
{
public GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
private int co_mV;
private int no2_mV;
LocationRequest mLocationRequest;
private boolean initiateApp;
String currentTime;
TcpClient mTcpClient;
ArrayList<Marker> markerArrayList;
static ArrayList<Double> markerLat = new ArrayList<>();
static ArrayList<Double> markerLng = new ArrayList<>();
static ArrayList<String> markerSnippet = new ArrayList<>();
static ArrayList<String> markerTitle = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
initiateApp = true;
markerArrayList = new ArrayList<>();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
markerArrayList.clear();
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
mMap.setMyLocationEnabled(true);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
}
}
else {
buildGoogleApiClient();
}
if (markerLat != null) {
addMapPoints();
}
}
/* Here we create the infoWindow **/
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle) {
getNewLocation();
new ConnectTask().execute("");
}
public void newData(JSONObject d) {
try {
co_mV = d.getInt("co_mV");
no2_mV = d.getInt("no2_mV");
} catch (JSONException e) {
e.printStackTrace();
}
getNewLocation();
}
public void getTime() {
Calendar cal = Calendar.getInstance();
currentTime = new SimpleDateFormat("HH:mm:ss").format(cal.getTime());
}
public void getNewLocation() {
mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
public void addMapPoints() {
markerArrayList = new ArrayList<>();
for (int i = 0; i < markerLat.size(); i++) {
LatLng latLng = new LatLng(markerLat.get(i), markerLng.get(i));
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(markerTitle.get(i));
markerOptions.snippet(markerSnippet.get(i));
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
Marker marker = mMap.addMarker(markerOptions);
markerArrayList.add(marker);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
if (markerArrayList.size()>1) {
if(location.distanceTo(mLastLocation) < 30) {
markerArrayList.get(markerArrayList.size()-1).remove();
markerArrayList.remove(markerArrayList.size()-1);
markerSnippet.remove(markerSnippet.size()-1);
markerTitle.remove(markerTitle.size()-1);
markerLat.remove(markerTitle.size()-1);
markerLng.remove(markerTitle.size()-1);
Toast.makeText(
getApplicationContext(),
"Reading to close to last reading, replaces last reading", Toast.LENGTH_SHORT).show();
}
}
if (markerArrayList.size() == 8) {
markerArrayList.get(0).remove();
markerArrayList.remove(0);
markerSnippet.remove(0);
markerTitle.remove(0);
markerLat.remove(0);
markerLng.remove(0);
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
if (co_mV != 0) {
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerLat.add(location.getLatitude());
markerLng.add(location.getLongitude());
markerOptions.title("Time of reading: " + currentTime);
markerTitle.add("Time of reading: " + currentTime);
markerOptions.snippet("co: " + String.valueOf(co_mV) + " mV, " + "no2: " + String.valueOf(no2_mV) + " mV");
markerSnippet.add("co: " + String.valueOf(co_mV) + " mV, " + "no2: " + String.valueOf(no2_mV) + " mV");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
markerArrayList.add(mCurrLocationMarker);
}
mLastLocation = location;
Log.d("ADebugTag", "Value: " + Double.toString(location.getLatitude()));
Log.d("ADebugTag", "Value: " + Double.toString(location.getLongitude()));
//move map camera
if(initiateApp){
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
}
boolean contains = mMap.getProjection()
.getVisibleRegion()
.latLngBounds
.contains(latLng);
if(!contains){
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
initiateApp = false;
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
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.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#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. Do the
// contacts-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
// Permission denied, 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.
// You can add here other case statements according to your requirement.
}
}
public JSONObject getNewJSON(JSONObject json) {
try {
int humidity = json.getInt("humidity_ppm");
int pressure = json.getInt("pressure_Pa");
int noise = json.getInt("noise_dB");
double lat = mLastLocation.getLatitude();
double lng = mLastLocation.getLongitude();
long time = System.currentTimeMillis() / 1000L;
JSONObject c = new JSONObject();
c.put("time",time);
c.put("lat",lat);
c.put("long",lng);
c.put("humidity",humidity);
c.put("pressure",pressure);
c.put("noise_dB",noise);
return c;
} catch (JSONException e) {
e.printStackTrace();
}
I solve this problem by exiting the application in onDestroy method .
I think when fragment is reused marker cannot be placed in map
#Override
public void onDestroy() {
getActivity().finish();
System.exit(0);
super.onDestroy();
}