Search code examples
androidgoogle-mapsgoogle-places-apiandroid-4.4-kitkat

Android studio API 19 : google places place not found api exception 15


I'm trying to develop an application which show nearby restaurants. Here is my code:

MapsActivity.java: public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;
private String API_KEY = BuildConfig.API_KEY;
PlacesClient placesClient;
private static final int RC_LOCATION = 10;
LatLng latLng;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    // Initialize the SDK
    Places.initialize(getApplicationContext(), API_KEY);

    // Create a new PlacesClient instance
    placesClient = Places.createClient(this);

    getCurrentLocation();
}

/**
 * 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;


}

private void getCurrentLocation() {
    List<Place.Field> placeFields = Arrays.asList(Place.Field.NAME, Place.Field.LAT_LNG,
            Place.Field.TYPES);

// Use the builder to create a FindCurrentPlaceRequest. FindCurrentPlaceRequest request = FindCurrentPlaceRequest.newInstance(placeFields);

// Call findCurrentPlace and handle the response (first check that the user has granted permission). if (ContextCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { Task placeResponse = placesClient.findCurrentPlace(request); placeResponse.addOnCompleteListener(task -> { if (task.isSuccessful()) { FindCurrentPlaceResponse response = task.getResult();

                boolean firstRestaurantFound = false;

                for (PlaceLikelihood placeLikelihood : response.getPlaceLikelihoods()) {
                    Log.i("success", String.format("Place '%s' has likelihood: %f",
                            placeLikelihood.getPlace().getName(),
                            placeLikelihood.getLikelihood()));

                    final Place.Type lookingFor = RESTAURANT; // Place.Type.RESTAURANT
                    // if latitude and longitude aren't null and if the place type is RESTAURANT
                    final List<Place.Type> types = placeLikelihood.getPlace().getTypes();
                    Log.d("TYPES", types.toString());
                    if (placeLikelihood.getPlace().getLatLng() != null && types.contains(lookingFor)) {

                        latLng = placeLikelihood.getPlace().getLatLng();

                        //Move camera to the first restaurant found
                        if(!firstRestaurantFound){
                            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
                            firstRestaurantFound = true;
                        }

                        MarkerOptions options = new MarkerOptions()
                                .position(latLng)
                                .title(placeLikelihood.getPlace().getName());

                        mMap.addMarker(options);
                    }

                }
            } else {
                Exception exception = task.getException();
                if (exception instanceof ApiException) {
                    ApiException apiException = (ApiException) exception;
                    Log.e("error", "Place not found: " + apiException.getStatusCode());
                }
            }
        });
    } else {
        getLocatePermission();

    }
}


private void getLocatePermission() {
    ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION}, RC_LOCATION);
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                       @NonNull int[] grantResults) {
    if (requestCode == RC_LOCATION) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            getCurrentLocation();
        } else {
            getLocatePermission();
        }
    }
}

}

But the emulator does not locate me and tell me Api exception 15: connection timed out. However it works on my samsung s10e android 10.


Solution

  • It works. I put manually my location in emulator parameters.