I've created a GPS-app, which shows my current location on a map on a Android Emulator via Android Studios. Now, as the title mentions, I've been trying to get the nearby places to work for a really long time now, without any success. As it seems, most of the video's and guides I've looked at has been updated, and I really don't know what to do. This is how my app currently looks like:
Application Image
I've created a button to locate all the resturants, since I have to start somewhere. I've created the API-key and enabled billing for places. I've fetched the demo api and created a model from it with different Pojo classes, such as Geometry, Location, MyPlaces, Photos, Results, etc. These contains methods that can be used to get information from the locations.
Now I need to create a method called something like nearByPlace();, but I don't know how to implement it correctly, and this is what I need a bit of help with. This is what my MapActivity looks like:
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private FusedLocationProviderClient mFusedLocationProviderClient;
private PlacesClient placesClient;
private List<AutocompletePrediction> predictionList;
private Location mLastKnownLocation;
private LocationCallback locationCallback;
private MaterialSearchBar materialSearchBar;
private View mapView;
private Button btnFind;
private RippleBackground rippleBg;
private final float DEFAULT_ZOOM = 15;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
materialSearchBar = findViewById(R.id.searchBar);
btnFind = findViewById(R.id.btn_find);
rippleBg = findViewById(R.id.ripple_bg);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mapView = mapFragment.getView();
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MapActivity.this);
Places.initialize(MapActivity.this, getString(R.string.google_maps_api));
placesClient = Places.createClient(this);
final AutocompleteSessionToken token = AutocompleteSessionToken.newInstance();
materialSearchBar.setOnSearchActionListener(new MaterialSearchBar.OnSearchActionListener() {
@override
public void onSearchStateChanged(boolean enabled) {
}
@override
public void onSearchConfirmed(CharSequence text) {
startSearch(text.toString(), true, null, true);
}
@override
public void onButtonClicked(int buttonCode) {
if (buttonCode == MaterialSearchBar.BUTTON_NAVIGATION) {
//opening or closing a navigation drawer
} else if (buttonCode == MaterialSearchBar.BUTTON_BACK) {
materialSearchBar.disableSearch();
}
}
});
materialSearchBar.addTextChangeListener(new TextWatcher() {
@override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@override
public void onTextChanged(CharSequence s, int start, int before, int count) {
FindAutocompletePredictionsRequest predictionsRequest = FindAutocompletePredictionsRequest.builder()
.setTypeFilter(TypeFilter.ADDRESS)
.setSessionToken(token)
.setQuery(s.toString())
.build();
placesClient.findAutocompletePredictions(predictionsRequest).addOnCompleteListener(new OnCompleteListener<FindAutocompletePredictionsResponse>() {
@override
public void onComplete(@NonNull Task<FindAutocompletePredictionsResponse> task) {
if (task.isSuccessful()) {
FindAutocompletePredictionsResponse predictionsResponse = task.getResult();
if (predictionsResponse != null) {
predictionList = predictionsResponse.getAutocompletePredictions();
List<String> suggestionsList = new ArrayList<>();
for (int i = 0; i < predictionList.size(); i++) {
AutocompletePrediction prediction = predictionList.get(i);
suggestionsList.add(prediction.getFullText(null).toString());
}
materialSearchBar.updateLastSuggestions(suggestionsList);
if (!materialSearchBar.isSuggestionsVisible()) {
materialSearchBar.showSuggestionsList();
}
}
} else {
Log.i("mytag", "prediction fetching task unsuccessful");
}
}
});
}
@override
public void afterTextChanged(Editable s) {
}
});
materialSearchBar.setSuggstionsClickListener(new SuggestionsAdapter.OnItemViewClickListener() {
@override
public void OnItemClickListener(int position, View v) {
if (position >= predictionList.size()) {
return;
}
AutocompletePrediction selectedPrediction = predictionList.get(position);
String suggestion = materialSearchBar.getLastSuggestions().get(position).toString();
materialSearchBar.setText(suggestion);
new Handler().postDelayed(new Runnable() {
@override
public void run() {
materialSearchBar.clearSuggestions();
}
}, 1000);
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
if (imm != null)
imm.hideSoftInputFromWindow(materialSearchBar.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);
final String placeId = selectedPrediction.getPlaceId();
List<Place.Field> placeFields = Arrays.asList(Place.Field.LAT_LNG);
FetchPlaceRequest fetchPlaceRequest = FetchPlaceRequest.builder(placeId, placeFields).build();
placesClient.fetchPlace(fetchPlaceRequest).addOnSuccessListener(new OnSuccessListener<FetchPlaceResponse>() {
@override
public void onSuccess(FetchPlaceResponse fetchPlaceResponse) {
Place place = fetchPlaceResponse.getPlace();
Log.i("mytag", "Place found: " + place.getName());
LatLng latLngOfPlace = place.getLatLng();
if (latLngOfPlace != null) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLngOfPlace, DEFAULT_ZOOM));
}
}
}).addOnFailureListener(new OnFailureListener() {
@override
public void onFailure(@NonNull Exception e) {
if (e instanceof ApiException) {
ApiException apiException = (ApiException) e;
apiException.printStackTrace();
int statusCode = apiException.getStatusCode();
Log.i("mytag", "place not found: " + e.getMessage());
Log.i("mytag", "status code: " + statusCode);
}
}
});
}
@override
public void OnItemDeleteListener(int position, View v) {
}
});
btnFind.setOnClickListener(new View.OnClickListener() {
@override
public void onClick(View v) {
LatLng currentMarkerLocation = mMap.getCameraPosition().target;
rippleBg.startRippleAnimation();
new Handler().postDelayed(new Runnable() {
@override
public void run() {
rippleBg.stopRippleAnimation();
startActivity(new Intent(MapActivity.this, PermissionsActivity.class));
finish();
}
}, 3000);
}
});
}
@SuppressLint("MissingPermission")
@override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
if (mapView != null && mapView.findViewById(Integer.parseInt("1")) != null) {
View locationButton = ((View) mapView.findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) locationButton.getLayoutParams();
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
layoutParams.setMargins(0, 0, 40, 180);
}
//check if gps is enabled or not and then request user to enable it
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(5000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
SettingsClient settingsClient = LocationServices.getSettingsClient(MapActivity.this);
Task<LocationSettingsResponse> task = settingsClient.checkLocationSettings(builder.build());
task.addOnSuccessListener(MapActivity.this, new OnSuccessListener<LocationSettingsResponse>() {
@override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
getDeviceLocation();
}
});
task.addOnFailureListener(MapActivity.this, new OnFailureListener() {
@override
public void onFailure(@NonNull Exception e) {
if (e instanceof ResolvableApiException) {
ResolvableApiException resolvable = (ResolvableApiException) e;
try {
resolvable.startResolutionForResult(MapActivity.this, 51);
} catch (IntentSender.SendIntentException e1) {
e1.printStackTrace();
}
}
}
});
mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
@override
public boolean onMyLocationButtonClick() {
if (materialSearchBar.isSuggestionsVisible())
materialSearchBar.clearSuggestions();
if (materialSearchBar.isSearchEnabled())
materialSearchBar.disableSearch();
return false;
}
});
}
@override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 51) {
if (resultCode == RESULT_OK) {
getDeviceLocation();
}
}
}
@SuppressLint("MissingPermission")
private void getDeviceLocation() {
mFusedLocationProviderClient.getLastLocation()
.addOnCompleteListener(new OnCompleteListener<Location>() {
@override
public void onComplete(@NonNull Task<Location> task) {
if (task.isSuccessful()) {
mLastKnownLocation = task.getResult();
if (mLastKnownLocation != null) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLastKnownLocation.getLatitude(), mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
} else {
final LocationRequest locationRequest = LocationRequest.create();
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(5000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationCallback = new LocationCallback() {
@override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
if (locationResult == null) {
return;
}
mLastKnownLocation = locationResult.getLastLocation();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLastKnownLocation.getLatitude(), mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
mFusedLocationProviderClient.removeLocationUpdates(locationCallback);
}
};
mFusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, null);
}
} else {
Toast.makeText(MapActivity.this, "unable to get last location", Toast.LENGTH_SHORT).show();
}
}
});
}
}