I'm working on a final year project and downloaded this code it was working but now I can't understand why it stops working it shows only Toasts, maybe a problem with API key can you help me please.
public class MapActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener,
GoogleMap.OnMarkerClickListener,
GoogleMap.OnMarkerDragListener {
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
int PROXIMITY_RADIUS = 20000;
double latitude, longitude;
double end_latitude, end_longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
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.map);
mapFragment.getMapAsync(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater= getMenuInflater();
menuInflater.inflate(R.menu.menu_item_maps, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Object dataTransfer[] = new Object[2];
GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
switch (item.getItemId()){
case R.id.map_menuitemresto:
mMap.clear();
dataTransfer = new Object[2];
String restaurant = "restaurant";
String url = getUrl(latitude, longitude, restaurant);
getNearbyPlacesData = new GetNearbyPlacesData();
dataTransfer[0] = mMap;
dataTransfer[1] = url;
getNearbyPlacesData.execute(dataTransfer);
Toast.makeText(MapActivity.this, "Showing Nearby Restaurants", Toast.LENGTH_LONG).show();
break;
}
return super.onOptionsItemSelected(item);
}
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;
//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);
}
mMap.setOnMarkerDragListener(this);
mMap.setOnMarkerClickListener(this);
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
public void onClick(View v)
{
Object dataTransfer[] = new Object[2];
GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
switch(v.getId()) {
case R.id.B_search: {
EditText tf_location = (EditText) findViewById(R.id.TF_location);
String location = tf_location.getText().toString();
List<Address> addressList = null;
MarkerOptions markerOptions = new MarkerOptions();
Log.d("location = ", location);
if (!location.equals("")) {
Geocoder geocoder = new Geocoder(this);
try {
addressList = geocoder.getFromLocationName(location, 5);
} catch (IOException e) {
e.printStackTrace();
}
if (addressList != null) {
for (int i = 0; i < addressList.size(); i++) {
Address myAddress = addressList.get(i);
LatLng latLng = new LatLng(myAddress.getLatitude(), myAddress.getLongitude());
markerOptions.position(latLng);
mMap.addMarker(markerOptions);
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
}
}
break;
case R.id.B_hotels:
//mMap.clear();
String hospital = "hotel";
String url = getUrl(latitude, longitude, hospital);
dataTransfer[0] = mMap;
dataTransfer[1] = url;
getNearbyPlacesData.execute(dataTransfer);
Toast.makeText(MapActivity.this, "Showing Nearby Hotels", Toast.LENGTH_LONG).show();
break;
case R.id.B_restaurant:
//mMap.clear();
dataTransfer = new Object[2];
String restaurant = "restaurant";
url = getUrl(latitude, longitude, restaurant);
getNearbyPlacesData = new GetNearbyPlacesData();
dataTransfer[0] = mMap;
dataTransfer[1] = url;
getNearbyPlacesData.execute(dataTransfer);
Toast.makeText(MapActivity.this, "Showing Nearby Restaurants", Toast.LENGTH_LONG).show();
break;
case R.id.B_diver:
//mMap.clear();
String school = "hotel";
dataTransfer = new Object[2];
url = getUrl(latitude, longitude, school);
getNearbyPlacesData = new GetNearbyPlacesData();
dataTransfer[0] = mMap;
dataTransfer[1] = url;
getNearbyPlacesData.execute(dataTransfer);
Toast.makeText(MapActivity.this, "Showing Nearby Hotels", Toast.LENGTH_LONG).show();
break;
case R.id.B_to:
dataTransfer = new Object[3];
url = getDirectionsUrl();
GetDirectionsData getDirectionsData = new GetDirectionsData();
dataTransfer[0] = mMap;
dataTransfer[1] = url;
dataTransfer[2] = new LatLng(end_latitude, end_longitude);
getDirectionsData.execute(dataTransfer);
break;
}
}
private String getDirectionsUrl()
{
StringBuilder googleDirectionsUrl = new StringBuilder("https://maps.googleapis.com/maps/api/directions/json?");
googleDirectionsUrl.append("origin="+latitude+","+longitude);
googleDirectionsUrl.append("&destination="+end_latitude+","+end_longitude);
googleDirectionsUrl.append("&key="+"AIzaSyBH5BAD65au_keEdICl_7KFxUzfT8OheVY");
return googleDirectionsUrl.toString();
}
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=" + "AIzaSyDN7RJFmImYAca96elyZlE5s_fhX-MMuhk");
Log.d("getUrl", googlePlacesUrl.toString());
return (googlePlacesUrl.toString());
}
#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);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
Log.d("onLocationChanged", "entered");
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.draggable(true);
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(MapActivity.this,"Your Current Location", Toast.LENGTH_LONG).show();
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
Log.d("onLocationChanged", "Removing Location Updates");
}
}
#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.
}
}
#Override
public boolean onMarkerClick(Marker marker) {
marker.setDraggable(true);
return false;
}
#Override
public void onMarkerDragStart(Marker marker) {
}
#Override
public void onMarkerDrag(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
end_latitude = marker.getPosition().latitude;
end_longitude = marker.getPosition().longitude;
Log.d("end_lat",""+end_latitude);
Log.d("end_lng",""+end_longitude);
}
public void changeTypeMap(View view) {
if (mMap.getMapType() == GoogleMap.MAP_TYPE_NORMAL) {
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
} else
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
}
I have a button to show nearby places with onClickListener
But this will not filter the places
private static final String TAG = "MapActivity";
private static final int PLACE_PICKER_REQUEST = 1;
YOUR_BUTTON = (Button) findViewById(R.id.YOUR_BUTTON_ID)
YOUR_BUTTON.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
try {
startActivityForResult(builder.build(MapActivity.this), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
Log.e(TAG, "onClick: Repairable: " + e.getMessage() );
} catch (GooglePlayServicesNotAvailableException e) {
Log.e(TAG, "onClick: NotAvailable: " + e.getMessage() );
}
}
});
Related
I am developing an android application that uses Google Maps.
The expected behavior is:
Enter the map activity
Ask user to use his location
Show nearby places
When I run the application using an emulator in Android Studio , the flow is the expected one (Pixel 2 Api 30), but when I run it on my phone, the permission is only asked for after I stop the application run.
Why is this happening?
Acitivity
public class NearbyPharmaciesActivity extends AppCompatActivity implements OnMapReadyCallback {
private static final int MY_PERMISSION_CODE = 1000;
private GoogleMap mMap;
private double latitude, longitude;
private Location lastLocation;
private Marker marker;
private GoogleMapsApi mService;
private FusedLocationProviderClient fusedLocationProviderClient;
private LocationCallback locationCallback;
private LocationRequest mLocationRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nearby_pharmacies);
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
// Init service
mService = RetrofitGoogleMaps.getApi();
// Request runtime permission
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.action_pharmacy:
nearbyPlaces("pharmacy");
break;
default:
break;
}
return true;
}
});
buildLocationCallBack();
buildLocationRequest();
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
fusedLocationProviderClient.requestLocationUpdates(mLocationRequest, locationCallback, Looper.myLooper());
}
private boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_BACKGROUND_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION) && ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_BACKGROUND_LOCATION)) {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_BACKGROUND_LOCATION
}, MY_PERMISSION_CODE);
} else {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_BACKGROUND_LOCATION
}, MY_PERMISSION_CODE);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case MY_PERMISSION_CODE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_BACKGROUND_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
buildLocationCallBack();
buildLocationRequest();
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
fusedLocationProviderClient.requestLocationUpdates(mLocationRequest, locationCallback, Looper.myLooper());
}
}
}
break;
}
}
private void buildLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(300000);
mLocationRequest.setFastestInterval(10000);
mLocationRequest.setSmallestDisplacement(30);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
private void buildLocationCallBack() {
System.out.println("Reached here");
locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
lastLocation = locationResult.getLastLocation();
System.out.println("last location: " + lastLocation.toString());
if (marker != null) {
marker.remove();
}
latitude = lastLocation.getLatitude();
longitude = lastLocation.getLongitude();
System.out.println("LATITUDE: " + latitude);
System.out.println("LONGITUDE: " + longitude);
LatLng latLng = new LatLng(latitude, longitude);
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("Your position")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
marker = mMap.addMarker(options);
//LocationData locationData = new LocationData(latitude, longitude);*/
//mDatabase.child("location").child(userId).child(String.valueOf(new Date().getTime())).setValue(locationData);
//getMarkers();
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
};
}
#Override
public void onMapReady(#NonNull GoogleMap googleMap) {
mMap = googleMap;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_BACKGROUND_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
} else {
mMap.setMyLocationEnabled(true);
}
}
}
private void nearbyPlaces(final String placeType) {
String url = getUrl(latitude, longitude, placeType);
System.out.println("URL: "+ url);
mService.getNearByPlaces(url)
.enqueue(new Callback<SearchResponse>() {
#Override
public void onResponse(Call<SearchResponse> call, Response<SearchResponse> response) {
if (response.isSuccessful()) {
System.out.println("Sucesso");
for (int i = 0; i < response.body().getResults().length; i++) {
System.out.println("ENTRA NO IF");
MarkerOptions markerOptions = new MarkerOptions();
Result googlePlace = response.body().getResults()[i];
double lat = Double.parseDouble(googlePlace.getGeometry().getLocation().getLat());
double lng = Double.parseDouble(googlePlace.getGeometry().getLocation().getLng());
String placeName = googlePlace.getName();
String vicinity = googlePlace.getVicinity();
LatLng latLng = new LatLng(lat, lng);
markerOptions.position(latLng);
markerOptions.title(placeName);
if (placeType.equals("pharmacy")) {
System.out.println("BEM");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
} else {
System.out.println("CONA");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
}
mMap.addMarker(markerOptions);
mMap.animateCamera(CameraUpdateFactory.zoomTo(13));
}
}
}
#Override
public void onFailure(Call<SearchResponse> call, Throwable t) {
}
});
}
private String getUrl(double latitude, double longitude, String placeType) {
StringBuilder builder = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
builder.append("location=" + latitude + "," + longitude);
builder.append("&radius=10000");
builder.append("&type=" + placeType);
builder.append("&sensor=true");
builder.append("&key=" + "XXXXXXXXXXXXXXXXXXXXXXXX");
Log.d("getUrl", builder.toString());
return builder.toString();
}
}
Found the problem.
This happened because I asked for permissions in two separate occasions.
First I would ask for SMS permissions in my Main Activity and then, when entering this Activity I would ask for location permissions.
In android development you must ask for all permissions at once.
I am using the places API to show places as markers on my map, I then want to be able to click on one of markers and save its information to firebase. At the moment when I save it to firebase it saves my current location instead of the markers lat long. pls help :)
mStar is the button that is clicked that once clicked I want to add the location to firebase...
mStar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(NearbyLocations.this, "Rating......", Toast.LENGTH_SHORT).show();
/*latitude = marker.getPosition().latitude;
longitude = marker.getPosition().longitude;*/
LocationInformation locInfo = new LocationInformation(name, latitude, longitude);
FirebaseUser user = mAuth.getCurrentUser();
String userID = user.getUid();
saveLocations.child(userID).child("Locations").setValue(locInfo)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(NearbyLocations.this, "Location saved", Toast.LENGTH_LONG).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(NearbyLocations.this, "Error location not saved", Toast.LENGTH_LONG).show();
}
});
}
});
this is the whole class as per requested in the comments.. thank you!!!!!
//imports
public class NearbyLocations extends AppCompatActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private Location lastLocation;
private String name, selPlace;
private double latitude, longitude;
private Marker currentUserLocationMarker;
private static final int Request_User_Location_Code = 99;
private ImageButton mStar, mHeart;
private LatLng selPlaceLatLng;
private String apiKey = "AIzaSyAiXcwMQY9v2ba4GvxLPsF_G-FPUJA5DUU";
private FirebaseAuth mAuth;
private FirebaseDatabase mFirebaseDatabase;
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference saveLocations;
private int ProximityRadius = 10000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nearby_locations);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
checkUserLocationPermission();
}
Places.initialize(getApplicationContext(), apiKey);
// Create a new Places client instance.
PlacesClient placesClient = Places.createClient(this);
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
saveLocations = mFirebaseDatabase.getReference();
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// 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);
mStar = (ImageButton) findViewById(R.id.btnStar);
//mHeart = (ImageButton) findViewById(R.id.btnHeart);
mStar.setVisibility(View.GONE);
//mHeart.setVisibility(View.GONE);
}
/**
* 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, Manifest.permission.ACCESS_FINE_LOCATION))
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
mStar.setVisibility(View.VISIBLE);
// mHeart.setVisibility(View.VISIBLE);
return false;
}
});
/*AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment)
getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment);
autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME));
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
Log.i(TAG, "Place: " + place.getName() + ", " + place.getId());
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i(TAG, "An error occurred: " + status);
}
});*/
mStar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(NearbyLocations.this, "Rating......", Toast.LENGTH_SHORT).show();
/*latitude = marker.getPosition().latitude;
longitude = marker.getPosition().longitude;*/
LocationInformation locInfo = new LocationInformation(name, latitude, longitude);
FirebaseUser user = mAuth.getCurrentUser();
String userID = user.getUid();
saveLocations.child(userID).child("Locations").setValue(locInfo).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(NearbyLocations.this, "Location saved", Toast.LENGTH_LONG).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(NearbyLocations.this, "Error location not saved", Toast.LENGTH_LONG).show();
}
});
}
});
}
public void starClick(Marker marker){
Toast.makeText(NearbyLocations.this, "Rating......", Toast.LENGTH_SHORT).show();
}
/*public void heartClick(Marker marker) {
Toast.makeText(NearbyLocations.this, "savig......", Toast.LENGTH_SHORT).show();
}
/*latitude = marker.getPosition().latitude;
longitude = marker.getPosition().longitude;
LocationInformation locInfo = new LocationInformation(name, latitude, longitude);
FirebaseUser user = mAuth.getCurrentUser();
String userID = user.getUid();
saveLocations.child(userID).child("Locations").setValue(locInfo).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(NearbyLocations.this, "Location saved", Toast.LENGTH_LONG).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(NearbyLocations.this, "Error location not saved", Toast.LENGTH_LONG).show();
}
});*/
/*public void pinClick(){
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
mMap.addMarker(new MarkerOptions().position(latLng).title("Clicked Location"));
}
});
}*/
protected synchronized void buildGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
public boolean checkUserLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location_Code);
} else {
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location_Code);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case Request_User_Location_Code:
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
if (googleApiClient == null ){
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
}
else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
return;
}
}
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
lastLocation = location;
if (currentUserLocationMarker != null){
currentUserLocationMarker.remove();
}
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("user Current Location");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
currentUserLocationMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomBy(12));
if(googleApiClient != null){
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
}
public void onClick(View v)
{
String hotel = "hotel";
String night_club = "night_club";
String restaurant = "restaurant";
Object transferData[] = new Object[2];
GetNearbyPlaces getNearbyPlaces = new GetNearbyPlaces();
//String url = getUrl(latitude, longitude);
switch (v.getId())
{
/*case R.id.search_address:
EditText addressField = (EditText) findViewById(R.id.location_search);
String address = addressField.getText().toString();
List<Address> addressList = null;
MarkerOptions userMarkerOptions = new MarkerOptions();
if (!TextUtils.isEmpty(address))
{
Geocoder geocoder = new Geocoder(this);
try
{
addressList = geocoder.getFromLocationName(address, 6);
if (addressList != null)
{
for (int i=0; i<addressList.size(); i++)
{
Address userAddress = addressList.get(i);
LatLng latLng = new LatLng(userAddress.getLatitude(), userAddress.getLongitude());
userMarkerOptions.position(latLng);
userMarkerOptions.title(address);
userMarkerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
mMap.addMarker(userMarkerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(10));
}
}
else
{
Toast.makeText(this, "Location not found...", Toast.LENGTH_SHORT).show();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
else
{
Toast.makeText(this, "please write any location name...", Toast.LENGTH_SHORT).show();
}
break;*/
case R.id.hotels_nearby:
mMap.clear();
String url = getUrl(latitude, longitude, hotel);
transferData[0] = mMap;
transferData[1] = url;
getNearbyPlaces.execute(transferData);
Toast.makeText(this, "Showing Nearby hotels...", Toast.LENGTH_SHORT).show();
break;
case R.id.clubs_nearby:
mMap.clear();
url = getUrl(latitude, longitude, night_club);
transferData[0] = mMap;
transferData[1] = url;
getNearbyPlaces.execute(transferData);
Toast.makeText(this, "Showing Nearby Night Clubs...", Toast.LENGTH_SHORT).show();
break;
case R.id.restaurants_nearby:
mMap.clear();
url = getUrl(latitude, longitude, restaurant);
transferData[0] = mMap;
transferData[1] = url;
getNearbyPlaces.execute(transferData);
Toast.makeText(this, "Showing Nearby Restaurants...", Toast.LENGTH_SHORT).show();
break;
}
}
private String getUrl(double latitude, double longitude, String nearbyPlace)
{
StringBuilder googleURL = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
googleURL.append("location=" + latitude + "," + longitude);
googleURL.append("&radius=" + ProximityRadius);
googleURL.append("&type=" + nearbyPlace);
googleURL.append("&sensor=true");
googleURL.append("&key=" + "AIzaSyAvKd4mDYNodZp-WfsT_AfpyyleH4BrKOI");
Log.d("NearbyLocations", "url = " + googleURL.toString());
return googleURL.toString();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
locationRequest = new LocationRequest();
locationRequest.setInterval(1100);
locationRequest.setFastestInterval(1100);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuLogout:
FirebaseAuth.getInstance().signOut();
finish();
startActivity(new Intent(this, LoginActivity.class));
break;
case R.id.menuProfile:
Intent intent = new Intent(this, ProfileActivity.class);
this.startActivity(intent);
break;
case R.id.menuAllUsers:
Intent intent1 = new Intent(this, AllUsers.class);
this.startActivity(intent1);
break;
case R.id.accountDetails:
Intent intent3 = new Intent(this, UpdateProfile.class);
this.startActivity(intent3);
break;
case R.id.menuLocation:
Intent intent2 = new Intent(this, MapsActivity.class);
this.startActivity(intent2);
break;
}
return true;
}
}
By looking at your code i found that you are assigning latitude and longitude inside void onLocationChanged(Location location) and that is why you are getting current location while clicking on star.
You should assign latitude and longitude inside onclick of marker as following.
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
latitude = marker.getPosition().latitude;
longitude = marker.getPosition().longitude;
return true;
}
});
Remove any other assignments and then click on star button,you should get proper location.
I am using nearbyPlaces web service and I have a problem, I am putting a marker on the map for each pharmacie that it finds, but the camera always move to the marker and it does not stay in the current user position dot.
this is the code
public class GetNearbyPlacesData extends AsyncTask<Object, String, String> {
String googlePlacesData;
GoogleMap mMap;
String url;
#Override
protected String doInBackground(Object... params) {
try {
Log.d("GetNearbyPlacesData", "doInBackground entered");
mMap = (GoogleMap) params[0];
url = (String) params[1];
DownloadUrl downloadUrl = new DownloadUrl();
googlePlacesData = downloadUrl.readUrl(url);
Log.d("GooglePlacesReadTask", "doInBackground Exit");
} catch (Exception e) {
Log.d("GooglePlacesReadTask", e.toString());
}
return googlePlacesData;
}
#Override
protected void onPostExecute(String result) {
Log.d("GooglePlacesReadTask", "onPostExecute Entered");
List<HashMap<String, String>> nearbyPlacesList = null;
DataParser dataParser = new DataParser();
nearbyPlacesList = dataParser.parse(result);
ShowNearbyPlaces(nearbyPlacesList);
Log.d("GooglePlacesReadTask", "onPostExecute Exit");
}
private void ShowNearbyPlaces(List<HashMap<String, String>> nearbyPlacesList) {
for (int i = 0; i < nearbyPlacesList.size(); i++) {
Log.d("onPostExecute","Entered into showing locations");
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
HashMap<String, String> googlePlace = nearbyPlacesList.get(i);
double lat = Double.parseDouble(googlePlace.get("lat"));
double lng = Double.parseDouble(googlePlace.get("lng"));
String placeName = googlePlace.get("place_name");
String vicinity = googlePlace.get("vicinity");
LatLng latLng = new LatLng(lat, lng);
markerOptions.position(latLng);
markerOptions.title(placeName + " : " + vicinity);
mMap.addMarker(markerOptions);
//markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(14.0f));
}
}
}
public class NearbyPharmaciesFragment extends Fragment implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
double latitude;
double longitude;
private int PROXIMITY_RADIUS = 1000;
LocationManager locationManager;
GoogleApiClient mGoogleApiClient;
AlertDialog alert = null;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_nearby_pharmacies, container, false);
locationManager = (LocationManager) getActivity().getSystemService(LOCATION_SERVICE);
if ( !locationManager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
AlertNoGps();
}
// Inflate the layout for this fragment
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) getActivity().getSupportFragmentManager()
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
return rootView;
}
private boolean CheckGooglePlayServices() {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result = googleAPI.isGooglePlayServicesAvailable(getActivity());
if(result != ConnectionResult.SUCCESS) {
if(googleAPI.isUserResolvableError(result)) {
googleAPI.getErrorDialog(getActivity(), 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(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
else {
buildGoogleApiClient();
mMap.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);
}
}
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=" + "API_KEY");
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));
float zoom=11.0f;
mMap.animateCamera(CameraUpdateFactory.zoomTo(zoom));
//Toast.makeText(getActivity(),"Your Current Location", Toast.LENGTH_LONG).show();
mMap.clear();
String pharmacy = "pharmacy";
String url = getUrl(latitude, longitude, pharmacy);
Object[] DataTransfer = new Object[2];
DataTransfer[0] = mMap;
DataTransfer[1] = url;
if (new InternetWatcher().isConnectedToNetwork(getActivity())){
GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
getNearbyPlacesData.execute(DataTransfer);
}else{
Toast.makeText(getActivity(), R.string.internet_para_ver_farmacias, Toast.LENGTH_LONG).show();
getActivity().onBackPressed();
}
//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(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
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.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(getActivity(),
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(getActivity(),
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(getActivity(), "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.
}
}
private void AlertNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.gps_no_activado_dialogo)
.setCancelable(false)
.setPositiveButton(R.string.si_gps, new DialogInterface.OnClickListener() {
public void onClick(#SuppressWarnings("unused") final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
getActivity().onBackPressed();
Toast.makeText(getActivity(), R.string.gps_Required, Toast.LENGTH_LONG).show();
dialog.cancel();
}
});
alert = builder.create();
alert.show();
}
Any help please? thanks in advance
Your posted code includes these lines:
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(14.0f));
Sounds like you don't want to move the camera, so you should probably delete them.
I've been following this tutorial on displaying nearby places, in my case I need nearby hospitals. I'm able to show my current location and display nearby hospitals. But what I want to do is add the telephone number of those hospitals being displayed. I've tried adding formatted_phone_number in my code but it doesn't display the correct phone number but instead displays "-NA-" which is the default in the event that there's no number available.
Any help would be greatly appreciated thanks!
Code Snippet of GetNearbyPlacesData class:
private void ShowNearbyPlaces(List<HashMap<String, String>> nearbyPlacesList) {
for (int i = 0; i < nearbyPlacesList.size(); i++) {
Log.d("onPostExecute","Entered into showing locations");
MarkerOptions markerOptions = new MarkerOptions();
HashMap<String, String> googlePlace = nearbyPlacesList.get(i);
double lat = Double.parseDouble(googlePlace.get("lat"));
double lng = Double.parseDouble(googlePlace.get("lng"));
String placeName = googlePlace.get("place_name");
String vicinity = googlePlace.get("vicinity");
String formatted_phone_number = googlePlace.get("formatted_phone_number");
LatLng latLng = new LatLng(lat, lng);
markerOptions.position(latLng);
markerOptions.title(placeName + " : " + vicinity);
markerOptions.snippet(vicinity + formatted_phone_number);
mMap.addMarker(markerOptions);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
}
}
DataParser class:
public class DataParser {
public List<HashMap<String, String>> parse(String jsonData) {
JSONArray jsonArray = null;
JSONObject jsonObject;
try {
Log.d("Places", "parse");
jsonObject = new JSONObject((String) jsonData);
jsonArray = jsonObject.getJSONArray("results");
} catch (JSONException e) {
Log.d("Places", "parse error");
e.printStackTrace();
}
return getPlaces(jsonArray);
}
private List<HashMap<String, String>> getPlaces(JSONArray jsonArray) {
int placesCount = jsonArray.length();
List<HashMap<String, String>> placesList = new ArrayList<>();
HashMap<String, String> placeMap = null;
Log.d("Places", "getPlaces");
for (int i = 0; i < placesCount; i++) {
try {
placeMap = getPlace((JSONObject) jsonArray.get(i));
placesList.add(placeMap);
Log.d("Places", "Adding places");
} catch (JSONException e) {
Log.d("Places", "Error in Adding places");
e.printStackTrace();
}
}
return placesList;
}
private HashMap<String, String> getPlace(JSONObject googlePlaceJson) {
HashMap<String, String> googlePlaceMap = new HashMap<String, String>();
String placeName = "-NA-";
String vicinity = "-NA-";
String formatted_phone_number = "-NA-";
String latitude = "";
String longitude = "";
String reference = "";
Log.d("getPlace", "Entered");
try {
if (!googlePlaceJson.isNull("name")) {
placeName = googlePlaceJson.getString("name");
}
if (!googlePlaceJson.isNull("vicinity")) {
vicinity = googlePlaceJson.getString("vicinity");
}
if (!googlePlaceJson.isNull("formatted_phone_number")) {
formatted_phone_number = googlePlaceJson.getString("formatted_phone_number");
}
latitude = googlePlaceJson.getJSONObject("geometry").getJSONObject("location").getString("lat");
longitude = googlePlaceJson.getJSONObject("geometry").getJSONObject("location").getString("lng");
reference = googlePlaceJson.getString("reference");
googlePlaceMap.put("place_name", placeName);
googlePlaceMap.put("vicinity", vicinity);
googlePlaceMap.put("formatted_phone_number", formatted_phone_number);
googlePlaceMap.put("lat", latitude);
googlePlaceMap.put("lng", longitude);
googlePlaceMap.put("reference", reference);
Log.d("getPlace", "Putting Places");
} catch (JSONException e) {
Log.d("getPlace", "Error");
e.printStackTrace();
}
return googlePlaceMap;
}
}
MapsActivity class:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
double latitude;
double longitude;
private int PROXIMITY_RADIUS = 20000;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
#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.map);
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;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//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) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
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();
}
});
}
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,
android.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"); //dito yung api key nasa sticky note
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,
android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
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.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{android.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,
android.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.
}
}
}
In MapsActivity.class, function getUrl() is taking "Hospital" as one of the arguments which is not in the list of supported types. So, the result type is default, since it doesn't match any supported types.
The response will give you all the places nearby search request for places of type 'default'. To make a request to Nearby Places API to get nearby hospitals, pass hospital instead of Hospital.
In the code, you make a request to Nearby Places API, formatted_phone_number is not returned in response. For more information, refer to the documentation.
To get the phone number(formatted_phone_number or international_phone_number) make a request to Place Details API with the PlaceId.
To get more clarity, enter the url in the browser and look at the response.
Hope this helps you. Good luck :)
I am developing an app,In this i am using google map to show user current location.The problem is when i open the app first time it shows blue map screen, and now i open the map again 2nd time then at this time map shows correct result with current location.This happen in targetsdkversion>23 and targetsdkversion<23 both the versions.Only the first time dosenot shows the correct map.Following is the code i am using.And how i validate the map whether map shows correct location or not ?
//java
public class Start_Activity1 extends FragmentActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
GoogleMap.OnMarkerDragListener,
GoogleMap.OnMapLongClickListener,
View.OnClickListener {
//Our Map
private GoogleMap mMap;
public static final int REQUEST_ID_ACCESS_COURSE_FINE_LOCATION = 100;
//To store longitude and latitude from map
private double longitude;
private double latitude;
String caddress;
EditText eddate;
EditText edtime;
EditText seats1 ;
public static TextView tvtime,tvdate;
Button btime,bdate;
//Buttons
private ImageButton buttonSave;
private ImageButton buttonCurrent;
private ImageButton buttonView;
private Button btnProceed, btnskip, btnClocation;
String strAdd, start_point, start_time, no_seats, mob_no, stime, seats;
TextView tvmap,textview;
int mYear, mMonth, mDay, mHour, mMinute;
private boolean loggedIn = false;
public static String email;
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 100;
private ProgressDialog myProgress;
//Google ApiClient
private GoogleApiClient googleApiClient;
SupportMapFragment mapFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
tvmap=(TextView)findViewById(R.id.tv_map);
textview=(TextView)findViewById(R.id.textView_euser);
tvdate=(TextView)findViewById(R.id.textView_sdate);
// tvtime=(TextView)findViewById(R.id.textView_stime);
seats1=(EditText)findViewById(R.id.editText_nseats);
//date and time
// datetime();
Calendar cal = Calendar.getInstance(TimeZone.getDefault());
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss a", Locale.getDefault());
tvdate.setText(cal.getTime().toLocaleString());
// tvtime.setText(sdf.format(cal.getTime()));
//progress bar
myProgress = new ProgressDialog(this);
myProgress.setTitle("Map Loading ...");
myProgress.setMessage("Please wait...");
myProgress.setCancelable(true);
// Display Progress Bar.
myProgress.show();
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
//Initializing googleapi client
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
//Initializing views and adding onclick listeners
btnProceed=(Button)findViewById(R.id.button_sproceed);
// btnskip=(Button)findViewById(R.id.button_skip);
// btnClocation=(Button)findViewById(R.id.button_clocation);
btnProceed.setOnClickListener(this);
// btnClocation.setOnClickListener(this);
}
#Override
protected void onResume() {
LocationManager mlocManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
boolean enabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(!enabled) {
showDialogGPS();
}
super.onResume();
}
private void showDialogGPS() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setTitle("Enable GPS");
builder.setMessage("Please enable GPS");
builder.setInverseBackgroundForced(true);
builder.setPositiveButton("Enable", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
startActivity(
new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
getCurrentLocation();
moveMap();
}
});
builder.setNegativeButton("Ignore", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
#Override
public void onClick(View v) {
if(v == btnProceed){
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF, false);
mob_no = sharedPreferences.getString(Config.PHONE_SHARED_PREF, "Not Available");
textview.setText(String.valueOf(mob_no));
// getCurrentLocation();
// moveMap();
if (loggedIn) {
//We will start the Profile Activity
submitForm();
hsubmitForm();
Intent i=new Intent(Start_Activity1.this,Index_Activity.class);
startActivity(i);
// smsForm();
// Toast.makeText(Start_Activity.this, "You Submitted Details Successfully", Toast.LENGTH_LONG).show();
}
}
}
//saving to database
private void submitForm() {
start_point = tvmap.getText().toString();
start_time = tvdate.getText().toString();
no_seats = seats1.getText().toString();
mob_no = textview.getText().toString();
// Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show();
new StartAsync(this).execute(start_point, start_time, no_seats, mob_no);
}
//saving to database
private void hsubmitForm() {
start_point = tvmap.getText().toString();
stime = tvdate.getText().toString();
seats = seats1.getText().toString();
mob_no = textview.getText().toString();
// Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show();
new SHistoryAsync(this).execute(mob_no, start_point, seats, stime);
}
private void smsForm() {
mob_no = textview.getText().toString();
// Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show();
new SmsAsync(this).execute(mob_no);
}
#Override
protected void onStart() {
googleApiClient.connect();
super.onStart();
}
#Override
protected void onStop() {
googleApiClient.disconnect();
super.onStop();
}
//Getting current location
private void getCurrentLocation() {
mMap.clear();
//Creating a location object
if(getApplicationInfo().targetSdkVersion>=23) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// 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.//
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
return;
}
}
else 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;
}
Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (location != null) {
//Getting longitude and latitude
longitude = location.getLongitude();
latitude = location.getLatitude();
// tvmap.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
// strAdd = getCompleteAddressString(latitude, longitude);
// tvmap.setText("Current Address : " + strAdd);
getCompleteAddressString(latitude, longitude);
//moving the map to location
moveMap();
}
}
//Function to move the map
private void moveMap() {
//String to display current latitude and longitude
String msg = latitude + ", "+longitude;
//Creating a LatLng Object to store Coordinates
LatLng latLng = new LatLng(latitude, longitude);
//Adding marker to map
mMap.addMarker(new MarkerOptions()
.position(latLng) //setting position
.draggable(true) //Making the marker draggable
.title("Current Location")); //Adding a title
//Moving the camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//Animating the camera
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng latLng = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(latLng).draggable(true));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.setOnMarkerDragListener(this);
mMap.setOnMapLongClickListener(this);
}
#Override
public void onConnected(Bundle bundle) {
getCurrentLocation();
myProgress.dismiss();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onMapLongClick(LatLng latLng) {
//Clearing all the markers
mMap.clear();
//Adding a new marker to the current pressed position
mMap.addMarker(new MarkerOptions()
.position(latLng)
.draggable(true));
}
#Override
public void onMarkerDragStart(Marker marker) {
}
#Override
public void onMarkerDrag(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
//Getting the coordinates
latitude = marker.getPosition().latitude;
longitude = marker.getPosition().longitude;
//Moving the map
moveMap();
}
#SuppressLint("LongLogTag")
private String getCompleteAddressString(double LATITUDE, double LONGITUDE) {
String strAdd = "";
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if (addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:");
for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
strAdd = strReturnedAddress.toString();
tvmap.setText(strAdd);
Log.w("My Current loction address", "" + strReturnedAddress.toString());
} else {
Log.w("My Current loction address", "No Address returned!");
}
} catch (Exception e) {
e.printStackTrace();
Log.w("My Current loction address", "Canont get Address!");
}
return strAdd;
}
#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
// contacts-related task you need to do.
// getCurrentLocation();
// moveMap();
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(Start_Activity1.this, "Permission denied", Toast.LENGTH_SHORT).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
}
the 'blue screen' is the atlantic ocean. it's because the first time the current location is 0,0. Out of this reason you should get the current location before starting the map.