java.lang.IllegalStateException: no included points - java

I am trying to list all the places according to the query type specified by the user. The app will show the map with markers of the places that are returned from the API call.
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
static String itemSelected;
PendingResult<PlaceLikelihoodBuffer> result;
static int clicked;
CharSequence[] items = {"accounting", "airport", "amusement_park", "aquarium", "art_gallery","atm","bakery","bank","bar","beauty_salon","bicycle_store","book_store","bowling_alley","bus_station","cafe"};
#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.
final SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mGoogleApiClient = new GoogleApiClient
.Builder(this)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.enableAutoManage(this,this)
.build();
final AlertDialog.Builder ad = new AlertDialog.Builder(this);
ad.setTitle("Pick a place")
.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.d("Demo", "Selected :" + items[which]);
clicked = which;
}
})
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#TargetApi(Build.VERSION_CODES.M)
#Override
public void onClick(DialogInterface dialog, int which) {
itemSelected = String.valueOf(items[clicked]);
Log.d("demo",itemSelected);
mapFragment.getMapAsync(MapsActivity.this);
}
})
.setCancelable(false);
AlertDialog alert = ad.create();
ad.show();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode)
{
case 100:
{
if(grantResults[0]== PackageManager.PERMISSION_GRANTED)
{
result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
#Override
public void onResult(#NonNull PlaceLikelihoodBuffer placeLikelihoods) {
Log.d("demo",placeLikelihoods.getStatus()+"");
}
});
}
else
{
Toast.makeText(this,"Permission denied by the user", Toast.LENGTH_LONG).show();
}
}
}
}
/**
* 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;
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
// TODO: Consider calling
MapsActivity.this.requestPermissions(new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},100);
// 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;
}
result= Places.PlaceDetectionApi.getCurrentPlace(mGoogleApiClient,null);
final PendingResult<PlaceLikelihoodBuffer> pbuff = Places.PlaceDetectionApi.getCurrentPlace(mGoogleApiClient,null);
pbuff.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
#Override
public void onResult(#NonNull PlaceLikelihoodBuffer placeLikelihoods) {
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for(PlaceLikelihood placeLikelihood : placeLikelihoods){
if (placeLikelihood.getPlace().getPlaceTypes().contains(itemSelected)){
mMap.addMarker(new MarkerOptions().position(placeLikelihood.getPlace().getLatLng()).title(placeLikelihood.getPlace().getName().toString()).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
builder.include(placeLikelihood.getPlace().getLatLng());
}
else{
mMap.addMarker(new MarkerOptions().position(placeLikelihood.getPlace().getLatLng()).title(placeLikelihood.getPlace().getName().toString()));
builder.include(placeLikelihood.getPlace().getLatLng());
}
}
placeLikelihoods.release();
LatLngBounds bounds = builder.build();
int padding = 10; // offset from edges of the map in pixels
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, padding);
mMap.animateCamera(cu);
//mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 10));
// Remove listener to prevent position reset on camera move.
//mMap.setOnCameraChangeListener(null);
// LatLngBounds.Builder bounds = new LatLngBounds.Builder();
// for (DataItem location : mUserLocations.keySet()) {
// bounds.include(new LatLng(
// Double.parseDouble(location.mData
// .get("latitude")), Double
// .parseDouble(location.mData
// .get("longitude"))));
// }
//
// LatLngBounds mapBounds;
// for (DataItem location : result. ) {
// if (mapBounds==null) {
// LatLng point = new LatLng(Double.parseDouble(location.pbuff.get("latitude")), Double.parseDouble(location.mData.get("longitude")))
// mapBounds =new LatLngBounds(point, point);
// } else {
// mapBounds = mapBounds.including(new LatLng(Double.parseDouble(location.mData.get("latitude")), Double.parseDouble(location.mData.get("longitude"))));
// }
// }
}
});
// 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"));
// mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
But the app crashes with the following error:
java.lang.IllegalStateException: no included points
at com.google.android.gms.common.internal.zzaa.zza(Unknown Source)
at
com.google.android.gms.maps.model.LatLngBounds$Builder.build(Unknown
Source).
I have tried various other links posted on SO, but nothing seems to work. Please help. This is my first question on SO, please let me know if I have done any mistakes.

Related

I want to add marker on my map using the latitude and longitude that i retrieve from my database

Does any one know what is the problem on my code? I want to add markers on my map using the latitude and longitude that i retrieved from my database. But no marker appeared. I am sure that I am receiveing the location from my database but I don't know why the marker did'nt appear
public class PassengerMainscreen_Activity extends AppCompatActivity implements OnMapReadyCallback {
boolean isPermissionGranted;
TextView textView;
DatabaseReference firebaseDatabase;
GoogleMap googleMap;
Marker marker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_passenger_mainscreen);
checkpermission();
textView = findViewById(R.id.LocEmpty);
//CHECKING GOOGLE PLAY SERVICES
if (isPermissionGranted) {
if (checkGooglePlayServices()) {
SupportMapFragment supportMapFragment = SupportMapFragment.newInstance();
getSupportFragmentManager().beginTransaction().add(R.id.CONTAINER, supportMapFragment).commit();
supportMapFragment.getMapAsync(this);
} else {
Toast.makeText(this, "Google Play Services Not available", Toast.LENGTH_SHORT).show();
}
}
}
private boolean checkGooglePlayServices() {
GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
int result = googleApiAvailability.isGooglePlayServicesAvailable(this);
if (result == ConnectionResult.SUCCESS) {
return true;
} else if (googleApiAvailability.isUserResolvableError(result)) {
Dialog dialog = googleApiAvailability.getErrorDialog(this, result, 201, new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
Toast.makeText(PassengerMainscreen_Activity.this, "User Cancelled Dialog", Toast.LENGTH_SHORT).show();
}
});
dialog.show();
}
return false;
}
private void checkpermission() {
Dexter.withContext(this).withPermission(Manifest.permission.ACCESS_FINE_LOCATION).withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
isPermissionGranted = true;
Toast.makeText(PassengerMainscreen_Activity.this, "Permission Granted", Toast.LENGTH_SHORT).show();
}
#Override
public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), "");
intent.setData(uri);
startActivity(intent);
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
permissionToken.continuePermissionRequest();
}
}).check(); //PERMISSION END
}
#Override
public void onMapReady(#NonNull GoogleMap googleMap) {
this.googleMap = googleMap;
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
}
googleMap.setMyLocationEnabled(true);
getbusLocation();
}
private void getbusLocation() {
firebaseDatabase = FirebaseDatabase.getInstance().getReference().child("Location");
firebaseDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
Double lat = Double.valueOf(snapshot.child("latitude").getValue().toString());
Double lng = Double.valueOf(snapshot.child("longitude").getValue().toString());
textView.setText(lat + "," + lng);
// DISPLAYING MARKER ON THE MAP
LatLng loc = new LatLng(lat, lng);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(loc);
marker = googleMap.addMarker(markerOptions);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
In this line of code where you are getting null pointer exception googleMap.addMarker(new MarkerOptions().position(loc).title("bus")); is because you have just declared variable googleMap but not initialised so you can initialise googleMap variable in onMapReady method as you are getting in parameter
Like this
#Override
public void onMapReady(#NonNull GoogleMap googleMap) {
this.googleMap = googleMap;
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
}
googleMap.setMyLocationEnabled(true);
// use googleMap variable after this only
}
but make sure you use googleMap variable only after it's initialisation so you have to move code of firebase into seperate function and call it after initialisation of googleMap

Marker disappearing and title not showing

I am trying to add a marker on my Google maps by long-pressing on the location and displaying the name of the location, however, whenever I long-press the marker appears for a split second and then goes away (disappears).
I understand after the long-press the marker is supposed to stay and then show the title as well, but that is not working.
Please do let me know if anyone is facing any such issue and can help me with it.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMapLongClickListener {
private GoogleMap mMap;
LocationManager locationManager;
LocationListener locationListener;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)==PackageManager.PERMISSION_GRANTED){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
centerMapOnLocation(lastKnownLocation, "Your Location");
}
}
}
public void centerMapOnLocation(Location location, String title) {
LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
mMap.clear();
if (title != "Your Location"){
mMap.addMarker(new MarkerOptions().position(userLocation).title(title));
}
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 10));
}
#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;
mMap.setOnMapLongClickListener(this);
Intent intent = getIntent();
if (intent.getIntExtra("placeNumber", 0) == 0) {
//zoom in on the user's location
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
centerMapOnLocation(location, "Your Location");
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
if (Build.VERSION.SDK_INT < 23) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// Activity#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 Activity#requestPermissions for more details.
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
} else {
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)==PackageManager.PERMISSION_GRANTED){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
centerMapOnLocation(lastKnownLocation, "Your Location");
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
}
}
}
}
#Override
public void onMapLongClick(LatLng latLng) {
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
String address ="";
try {
List <Address> listAddresses= geocoder.getFromLocation(latLng.latitude,latLng.longitude,1);
if (listAddresses!=null&& listAddresses.size()>0){
if (listAddresses.get(0).getThoroughfare()!=null){
if (listAddresses.get(0).getSubThoroughfare()!=null){
address+=listAddresses.get(0).getSubThoroughfare()+" ";
}
address+= listAddresses.get(0).getThoroughfare();
}
}
} catch (IOException e) {
e.printStackTrace();
}
if (address == ""){
SimpleDateFormat sdf = new SimpleDateFormat("mm:HH yyyyMMdd", Locale.getDefault());
address = sdf.format(new Date());
}
mMap.addMarker(new MarkerOptions().position(latLng).title(address).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)));
}
}
You are clearing your map every time your location changes here:
#Override
public void onLocationChanged(Location location) {
centerMapOnLocation(location, "Your Location");
}
That's why your marker disappears right after you add it to the map. If you remove or comment out this line within your centerMapOnLocation method:
mMap.clear();
Then the markers no longer disappear.
Hope this helps!

How to track friends location?

I am new in this field and I am trying to make application to track my friends like "snap-map". I am able to get my real-time location but I don't know what should I add to get real-time location of people who are using same application.
Here is my Java code, it will really helpful for me if you guys give me a code.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
private FirebaseAuth mAuth;
final static int PERMISSION_ALL = 1;
final static String[] PERMISSIONS = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION};
private GoogleMap mMap;
MarkerOptions mo;
Marker marker;
private Location user;
LocationManager locationManager;
private HashMap<Float, Location> otherUser = new HashMap<Float, Location>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
mAuth = FirebaseAuth.getInstance();
// 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);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
mo = new MarkerOptions().position(new LatLng(0, 0)).title("My Current Location");
if (Build.VERSION.SDK_INT >= 27 && !isPermissionGranted()) {
requestPermissions(PERMISSIONS, PERMISSION_ALL);
} else requestLocation();
if (!isLocationEnabled())
showAlert(1);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
marker = mMap.addMarker(mo);
}
//Called when the location has changed.
#Override
public void onLocationChanged(Location location) {
LatLng myCoordinates = new LatLng(location.getLatitude(), location.getLongitude());
marker.setPosition(myCoordinates);
mMap.moveCamera(CameraUpdateFactory.newLatLng(myCoordinates));
}
//Called when the provider status changes.
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
//Called when the provider is enabled by the user.
#Override
public void onProviderEnabled(String provider) {
}
//Called when the provider is disabled by the user. If requestLocationUpdates
#Override
public void onProviderDisabled(String provider) {
}
private void requestLocation() {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.POWER_HIGH);
String provider = locationManager.getBestProvider(criteria, true);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
}
locationManager.requestLocationUpdates(provider, 10000, 10, this);
}
private boolean isLocationEnabled() {
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
private boolean isPermissionGranted() {
if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
== PackageManager.PERMISSION_GRANTED || checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
Log.v("mylog","Permission is granted");
return true;
}else{
Log.v("mylog","Permission not granted");
return false;
}
}
private void showAlert(final int status) {
String message, title, btnText;
if (status == 1) {
message = "Your Locations Settings is set to 'Off'.\nPlease Enable Location to " +
"use this app";
title = "Enable Location";
btnText = "Location Settings";
} else {
message = "Please allow this app to access location!";
title = "Permission access";
btnText = "Grant";
}
final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setCancelable(false);
dialog.setTitle(title)
.setMessage(message)
.setPositiveButton(btnText, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
if (status == 1) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
} else
requestPermissions(PERMISSIONS, PERMISSION_ALL);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
finish();
}
});
dialog.show();
}

display current location in MapFragment

I have a location class which creates an instance on MapFragment, and dependant on which activity the map is created from, will drop a different marker. I would also like the map to display a marker for the phones current location.
I'm assuming I can do something like this, but I cant work out how to get and update the phones current coordinates and assign that to myLocation.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
MapFragment googleMap = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
googleMap.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap nMap){
if(MainMenu.bkSource == true) {
LatLng bkLatLng = new LatLng(54.5816008, -5.9651271);
LatLng myLocation = new LatLng(???);
nMap.addMarker(new MarkerOptions().position(bkLatLng).title("Burger King, Boucher Road"));
nMap.addMarker(new MarkerOptions().position(myLocation).title("You Are Here");
nMap.moveCamera(CameraUpdateFactory.newLatLngZoom(bkLatLng, 15));
nMap.animateCamera(CameraUpdateFactory.zoomTo(18.0f));
}
if(MainMenu.kfcSource == true){
LatLng bkLatLng = new LatLng(54.5771914, -5.9620562);
nMap.addMarker(new MarkerOptions().position(bkLatLng).title("KFC, Boucher Road"));
nMap.moveCamera(CameraUpdateFactory.newLatLngZoom(bkLatLng, 15));
nMap.animateCamera(CameraUpdateFactory.zoomTo(18.0f));
}
if(MainMenu.mcdSource == true){
LatLng bkLatLng = new LatLng(54.5879486, -5.9580009);
nMap.addMarker(new MarkerOptions().position(bkLatLng).title("McDonald's, Boucher Road"));
nMap.moveCamera(CameraUpdateFactory.newLatLngZoom(bkLatLng, 15));
nMap.animateCamera(CameraUpdateFactory.zoomTo(18.0f));
}
}
Here is an example Fragment that extends SupportMapFragment, on launch it will get the user's current location, place a Marker, and zoom in:
public class MapFragment extends SupportMapFragment
implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
GoogleMap mGoogleMap;
SupportMapFragment mapFrag;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
#Override
public void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mGoogleMap == null) {
getMapAsync(this);
}
}
#Override
public void onPause() {
super.onPause();
//stop location updates when Activity is no longer active
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onMapReady(GoogleMap googleMap)
{
mGoogleMap=googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Location Permission already granted
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
}
else {
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.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(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {}
#Override
public void onLocationChanged(Location location)
{
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
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 = mGoogleMap.addMarker(markerOptions);
//move map camera
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,11));
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
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(getActivity())
.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(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(getActivity(),
new String[]{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(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mGoogleMap.setMyLocationEnabled(true);
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(getActivity(), "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
}
Since the Location permission request needs to go through the Activity, you will need to route the result from the Activity to the Fragment's onRequestPermissionsResult() method:
public class MainActivity extends AppCompatActivity {
MapFragment mapFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mapFragment = new MapFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.mapframe, mapFragment);
transaction.commit();
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
if (requestCode == MapFragment.MY_PERMISSIONS_REQUEST_LOCATION){
mapFragment.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
The layout just contains a FrameLayout where the MapFragment goes.
activity_main.xml:
Use the following code for get current location:
#Override
public void onMapReady(GoogleMap googleMap) {
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;
}
mMap.setMyLocationEnabled(true);
}
If you want to add marker in current Location try this:
1.Implement LocationListener In your Activity.
2.Update LocationRequest:
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(5000); //5 seconds
mLocationRequest.setFastestInterval(3000); //3 seconds
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
3.create your marker on onLocationChanged(Location location)
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
//place marker at current position
//mGoogleMap.clear();
Marker currLocationMarker;
if (currLocationMarker != null) {
currLocationMarker.remove();
}
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));
currLocationMarker = mMap.addMarker(markerOptions);
}
}

Heat Maps are not displaying in fragment

I'm trying to display heatmap points in android using google maps utility library, nothing is displayed on the map. I don't know if I need something else, I've looked at examples but in my case it doesn't work. I'm using fragments.
public class MapFragment extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
private HeatmapTileProvider mProvider;
protected LatLng mCenterLocation = new LatLng( 39.7392, -104.9903 );
public MapFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_map, container, false);
mMapView = (MapView) rootView.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume(); // needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
// For showing a move to my location button
if (ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), 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;
}
googleMap.setMyLocationEnabled(true);
// For dropping a marker at a point on the Map
LatLng colorado = new LatLng(39.7392, -104.9903);
googleMap.addMarker(new MarkerOptions().position(colorado).title("Marker Title").snippet("Marker Description"));
// For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(colorado).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
addHeatMap();
}
});
return rootView;
}
public void addHeatMap(){
ArrayList<LatLng> locations = generateLocations();
mProvider = new HeatmapTileProvider.Builder().data(locations).build();
mProvider.setRadius(HeatmapTileProvider.DEFAULT_RADIUS );
googleMap.addTileOverlay(new TileOverlayOptions().tileProvider(mProvider));
}
private ArrayList<LatLng> generateLocations() {
ArrayList<LatLng> locations = new ArrayList<LatLng>();
double lat;
double lng;
Random generator = new Random();
for (int i = 0; i < 1000; i++) {
lat = generator.nextDouble() / 3;
lng = generator.nextDouble() / 3;
if (generator.nextBoolean()) {
lat = -lat;
}
if (generator.nextBoolean()) {
lng = -lng;
}
locations.add(new LatLng(mCenterLocation.latitude + lat, mCenterLocation.longitude + lng));
}
return locations;
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
}
Checking the Heatmaps guide, I don't see any issues about it. Try to call clearTileCache(), its indicated in its API reference that you should call it after setRadius.

Categories