Google map to find current location and nearby places - android

I want to add a Google Maps plugin in my Android app to fetch the current location of a user and show nearby hospitals.
How to fetch the current location and nearby places? Could somebody give me a direction on it?

Please follow the following code you will get nearby hospitals it's working.:)
You Can change this type at your own will, e.g hospital, cafe, restaurant.... and see how it all works:
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback,
LocationListener {
private GoogleMap mMap;
LocationManager locationManager;
CoordinatorLayout mainCoordinatorLayout;
String type;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!isGooglePlayServicesAvailable()) {
return;
}
setContentView(R.layout.activity_maps);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
type="hospital";
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mainCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.mainCoordinatorLayout);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
showLocationSettings();
}
}
private void showLocationSettings() {
Snackbar snackbar = Snackbar
.make(mainCoordinatorLayout, "Location Error: GPS Disabled!",
Snackbar.LENGTH_LONG)
.setAction("Enable", new View.OnClickListener() {
#Override public void onClick(View v) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
});
snackbar.setActionTextColor(Color.RED);
snackbar.setDuration(Snackbar.LENGTH_INDEFINITE);
View sbView = snackbar.getView();
TextView textView = (TextView) sbView
.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = 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) {
return;
}
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
showCurrentLocation();
}
private void showCurrentLocation() {
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
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) {
return;
}
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(bestProvider, MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
}
private void loadNearByPlaces(double latitude, double longitude) {
StringBuilder googlePlacesUrl =
new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
googlePlacesUrl.append("location=").append(latitude).append(",").append(longitude);
googlePlacesUrl.append("&radius=").append(PROXIMITY_RADIUS);
googlePlacesUrl.append("&types=").append(type);
googlePlacesUrl.append("&sensor=true");
googlePlacesUrl.append("&key=" + GOOGLE_BROWSER_API_KEY);
JsonObjectRequest request = new JsonObjectRequest(googlePlacesUrl.toString(),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject result) {
Log.i(TAG, "onResponse: Result= " + result.toString());
parseLocationResult(result);
}
},
new Response.ErrorListener() {
#Override public void onErrorResponse(VolleyError error) {
Log.e(TAG, "onErrorResponse: Error= " + error);
Log.e(TAG, "onErrorResponse: Error= " + error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(request);
}
private void parseLocationResult(JSONObject result) {
String id, place_id, placeName = null, reference, icon, vicinity = null;
double latitude, longitude;
try {
JSONArray jsonArray = result.getJSONArray("results");
if (result.getString(STATUS).equalsIgnoreCase(OK)) {
mMap.clear();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject place = jsonArray.getJSONObject(i);
id = place.getString(SUPERMARKET_ID);
place_id = place.getString(PLACE_ID);
if (!place.isNull(NAME)) {
placeName = place.getString(NAME);
}
if (!place.isNull(VICINITY)) {
vicinity = place.getString(VICINITY);
}
latitude = place.getJSONObject(GEOMETRY).getJSONObject(LOCATION)
.getDouble(LATITUDE);
longitude = place.getJSONObject(GEOMETRY).getJSONObject(LOCATION)
.getDouble(LONGITUDE);
reference = place.getString(REFERENCE);
icon = place.getString(ICON);
MarkerOptions markerOptions = new MarkerOptions();
LatLng latLng = new LatLng(latitude, longitude);
markerOptions.position(latLng);
markerOptions.title(placeName + " : " + vicinity);
mMap.addMarker(markerOptions);
}
Toast.makeText(getBaseContext(), jsonArray.length() + " Supermarkets found!",
Toast.LENGTH_LONG).show();
} else if (result.getString(STATUS).equalsIgnoreCase(ZERO_RESULTS)) {
Toast.makeText(getBaseContext(), "No Supermarket found in 5KM radius!!!",
Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
Log.e(TAG, "parseLocationResult: Error=" + e.getMessage());
}
}
#Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(latLng).title("My Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
loadNearByPlaces(latitude, longitude);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
private boolean isGooglePlayServicesAvailable() {
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (apiAvailability.isUserResolvableError(resultCode)) {
apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.i(TAG, "This device is not supported.");
finish();
}
return false;
}
return true;
}
}
Here is the xml file.
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<fragment android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
</FrameLayout>
its workind at my side. please add the api key and enjoy it.Hope this help:)

Related

show the current position of the user on google maps with a marker and the positions of different stations received from the server

hello everyone I am doing a university project and I have to show on google maps the railway stations received from the Server (with a marker and PolylineOptions) and the current position of the user (with a marker). The problem is showing the user's current location (the problem is the code shown in ** bold). My code is:
public class MapsLine extends Fragment {
private String sid_user;
private int did;
GoogleMap map;
private static final int MY_PERMISSION_REQUEST_ACCESS_FINE_LOCATION = 0;
Location currentLocation;
FusedLocationProviderClient fusedLocationProviderClient;
private static final int REQUEST_CODE = 101;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_maps_line, container, false);
**SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
fetchLocation();**
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
map = mMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
MarkerOptions markerOptions = new MarkerOptions().position(latLng).title("I am here!");
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 5));
mMap.addMarker(markerOptions);
mMap.clear();
PolylineOptions polyline1 = new PolylineOptions();
List<LatLng> routeArray = new ArrayList<LatLng>();
JSONObject requestParam = new JSONObject();
String GET_STATIONS = "https://helpme.php";
try {
requestParam.put("did", did);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest req = new JsonObjectRequest(
Request.Method.POST,
GET_STATIONS,
requestParam,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray stations_array = response.getJSONArray("stations");
Log.d("main_activity_sid_map", stations_array.toString());
Log.d("main_activity_sid_map", String.valueOf(stations_array.length()));
for (int j = 0; j < stations_array.length(); j++) {
JSONObject stations = stations_array.getJSONObject(j);
String name = stations.getString("sname");
String lat = stations.getString("lat");
String lon = stations.getString("lon");
Log.d("main_activity_sid_map", name);
Log.d("main_activity_sid_map", lat);
Log.d("main_activity_sid_map", lon);
polyline1.add(new LatLng(Float.parseFloat(lat),Float.parseFloat(lon)));
polyline1.color(Color.RED);
LatLng latLng = new LatLng(Float.parseFloat(lat), Float.parseFloat(lon));
mMap.addMarker(new MarkerOptions().position(latLng).title("Marker in " + name));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
LatLng from_Latlng = new LatLng(Float.parseFloat(lat), Float.parseFloat(lon));
if (!routeArray.contains(latLng)) {
routeArray.add(latLng);
}
}
} catch (Exception e) {
e.printStackTrace();
return;
}
drawLine(routeArray);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
MainActivity.requestQueue.add(req);
}
});
return rootView;
}
**private void fetchLocation() {
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_CODE);
return;
}
Task<Location> task = fusedLocationProviderClient.getLastLocation();
task.addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
currentLocation = location;
Toast.makeText(getActivity().getApplicationContext(), currentLocation.getLatitude() + "" + currentLocation.getLongitude(), Toast.LENGTH_SHORT).show();
SupportMapFragment supportMapFragment = (SupportMapFragment) getParentFragmentManager().findFragmentById(R.id.map);
assert supportMapFragment != null;
supportMapFragment.getMapAsync((OnMapReadyCallback) MapsLine.this);
}
}
});
}**
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case MY_PERMISSION_REQUEST_ACCESS_FINE_LOCATION:
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted
Log.d("Location", "Now the permission is granted");
} else {
// permission was not granted
Log.d("Location", "Permission still not granted");
}
break;
}
}
public void drawLine(List<LatLng> points) {
if (points == null) {
Log.e("Draw Line", "got null as parameters");
return;
}
Polyline line = map.addPolyline(new PolylineOptions().color(Color.RED));
line.setPoints(points);
LatLngBounds.Builder builder = new LatLngBounds.Builder();
}
}
My code does not start. How can I implement the current position of the user and the positions of the stations, received from the server?

How to click on marker produced by places API and find the lat/long of that marker and then upload to firebase

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.

Google Maps Nearby Places shows only Toasts

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() );
}
}
});

How to get current accurate location using GPS provider?

i need current location of user with the help of GPS provider.
Currently i'm getting GPS location, but in some devices i'm not getting location.
I also tried last known location and network location, but they are not accurate.
So please help by providing better solution.
My current code:
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
MapsInitializer.initialize(getActivity());
LocationListener listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
final double latitude = location.getLatitude();
final double longitude = location.getLongitude();
if (getActivity() == null){
return;
}
Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());
try {
List<Address> fromLocation = geocoder.getFromLocation(latitude, longitude, 1);
Address address = null;
if (fromLocation != null && fromLocation.size() > 0) {
address = fromLocation.get(0);
final String locality = address.getLocality();
if (dataSend != null) {
dataSend.onDataSend(address);
}
fragmentMapBinding.map.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
LatLng latLng = new LatLng(latitude, longitude);
googleMap.clear();
CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(new CameraPosition(latLng, 19, 0, 0));
googleMap.animateCamera(cameraUpdate);
googleMap.getUiSettings().setZoomGesturesEnabled(false);
googleMap.getUiSettings().setScrollGesturesEnabled(false);
googleMap.addMarker(new MarkerOptions().position(latLng).title("Your Location"));
}
});
}
} catch (IOException e) {
Log.e(TAG, "getMap", e);
}
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
Toast.makeText(getActivity(), s + " : " + i, Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String s) {
Toast.makeText(getActivity(), s, Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String s) {
Toast.makeText(getActivity(), s, Toast.LENGTH_SHORT).show();
}
};
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);

When placing markers on map activity the camera move to the marker

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.

Categories

Resources