I am trying to implement something similar to this (https://github.com/ankitsinghmyself/SearchNearByPlace) in my Android application. I have tried running the persons code straight from GitHub with my own API key and it works but will not allow Nearby Search.
I have tried two YouTube tutorials and two GitHub repos and no luck with Nearby Search. Can anyone please shed some light on why this is causing me issues?
I have Places and SDK API with billing account, and have added the correct dependencies etc. The map works fine with my current location, but the buttons will not show the nearby locations.
Here is what I have, it’s quite a lot, so if you need more information from me please ask:
MapsActivity:
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private FusedLocationProviderClient mFusedLocationProviderClient;
private Location mLastKnownLocation;
private LocationCallback locationCallback;
// private MaterialSearchBar materialSearchBar;
private View mapView;
private Button btnFind;
double latitude,longitude;
// private RippleBackground rippleBg;
private final float DEFAULT_ZOOM = 15;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mapView = mapFragment.getView();
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MapsActivity.this);
Places.initialize(MapsActivity.this, getString(R.string.google_maps_key));
}
@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(MapsActivity.this);
Task<LocationSettingsResponse> task = settingsClient.checkLocationSettings(builder.build());
task.addOnSuccessListener(MapsActivity.this, new OnSuccessListener<LocationSettingsResponse>() {
@Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
getDeviceLocation();
}
});
task.addOnFailureListener(MapsActivity.this, new OnFailureListener() {
@Override
public void onFailure(Exception e) {
if (e instanceof ResolvableApiException) {
ResolvableApiException resolvable = (ResolvableApiException) e;
try {
resolvable.startResolutionForResult(MapsActivity.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;
}
});
}
public void onClick(View v)
{
Object[] dataTransfer = new Object[2];
GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
switch(v.getId())
{
case R.id.btn_hospital:
mMap.clear();
String hospital = "hospital";
String url = getUrl(latitude, longitude, hospital);
dataTransfer[0] = mMap;
dataTransfer[1] = url;
getNearbyPlacesData.execute(dataTransfer);
Toast.makeText(MapsActivity.this, "Searching Nearby Hospitals", Toast.LENGTH_LONG).show();
break;
case R.id.btn_library:
mMap.clear();
String school = "library";
url = getUrl(latitude, longitude, school);
dataTransfer[0] = mMap;
dataTransfer[1] = url;
getNearbyPlacesData.execute(dataTransfer);
Toast.makeText(MapsActivity.this, "Searching Nearby Schools", Toast.LENGTH_LONG).show();
break;
case R.id.btn_restaurant:
mMap.clear();
String lib = "restaurant";
url = getUrl(latitude, longitude, lib);
dataTransfer[0] = mMap;
dataTransfer[1] = url;
getNearbyPlacesData.execute(dataTransfer);
Toast.makeText(MapsActivity.this, "Searching Nearby Libraries...", Toast.LENGTH_LONG).show();
break;
}
}
private String getUrl(double latitude , double longitude , String nearbyPlace)
{
StringBuilder googlePlaceUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
googlePlaceUrl.append("location="+latitude+","+longitude);
googlePlaceUrl.append("&radius="+ 5000);
googlePlaceUrl.append("&type="+ nearbyPlace);
googlePlaceUrl.append("&sensor=true");
googlePlaceUrl.append("&key="+ R.string.google_maps_key);
Log.d("MapsActivity", "url = "+googlePlaceUrl.toString());
return googlePlaceUrl.toString();
}
@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(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(MapsActivity.this, "unable to get last location", Toast.LENGTH_SHORT).show();
}
}
});
}
}
FindNearby:
class GetNearbyPlacesData extends AsyncTask<Object, String, String> {
private String googlePlacesData;
private GoogleMap mMap;
String url;
@Override
protected String doInBackground(Object... objects){
mMap = (GoogleMap)objects[0];
url = (String)objects[1];
DownloadUrl downloadURL = new DownloadUrl();
try {
googlePlacesData = downloadURL.readUrl(url);
} catch (IOException e) {
e.printStackTrace();
}
return googlePlacesData;
}
@Override
protected void onPostExecute(String s){
List<HashMap<String, String>> nearbyPlaceList;
DataParser parser = new DataParser();
nearbyPlaceList = parser.parse(s);
Log.d("nearbyplacesdata","called parse method");
showNearbyPlaces(nearbyPlaceList);
}
private void showNearbyPlaces(List<HashMap<String, String>> nearbyPlaceList)
{
for(int i = 0; i < nearbyPlaceList.size(); i++)
{
MarkerOptions markerOptions = new MarkerOptions();
HashMap<String, String> googlePlace = nearbyPlaceList.get(i);
String placeName = googlePlace.get("place_name");
String vicinity = googlePlace.get("vicinity");
double lat = Double.parseDouble(Objects.requireNonNull(googlePlace.get("lat")));
double lng = Double.parseDouble(Objects.requireNonNull(googlePlace.get("lng")));
LatLng latLng = new LatLng( lat, lng);
markerOptions.position(latLng);
markerOptions.title(placeName + " : "+ vicinity);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(12));
}
}
}
Source: Android Questions
One Reply to “Nearby Search Places API Not Working on Android Studio”
this app i did please contact me i will tell how to do
email: [email protected]