Моя функция getNearbyRestaurant не вызывается для размещения маркеров в GoogleMap - PullRequest
0 голосов
/ 15 апреля 2020
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map);
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.google_map);


    restaurantNearbyRef = FirebaseDatabase.getInstance().getReference().child("Restaurant").child("Info");
    fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);


    fetchLastLocation();
    getNearbyRestaurant();


}


private ArrayList<Marker> restaurantMarker = new ArrayList<>();

private void fetchLastLocation() {

    if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
        ActivityCompat.requestPermissions(this, 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) {

                mCurrentLocation = location;
                Toast.makeText(getApplicationContext(), mCurrentLocation.getLatitude()
                        + "" + mCurrentLocation.getLongitude(), Toast.LENGTH_SHORT).show();
                SupportMapFragment supportMapFragment = (SupportMapFragment)
                        getSupportFragmentManager().findFragmentById(R.id.google_map);
                supportMapFragment.getMapAsync(MapActivity.this);

                latitude = mCurrentLocation.getLatitude();
                longitude = mCurrentLocation.getLongitude();

                Log.d(TAG, "The latitude is " + latitude + " and the longitude is " + longitude);
            }

        }

    });

}


public void getNearbyRestaurant(){
    if (restaurantMarker != null) {
        for (Marker marker : restaurantMarker) {
            marker.remove();
        }
    }

    GeoFire geoFire = new GeoFire(restaurantNearbyRef);

    GeoQuery geoQuery = geoFire.queryAtLocation(new GeoLocation(latitude,longitude),radius);
    geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
        @Override
        public void onKeyEntered(String key, GeoLocation location) {
            restaurantMarker
                    .add(mMap.addMarker(new MarkerOptions().title("Restaurant").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))
                            .position(new LatLng(location.latitude, location.longitude))));

            Log.d(TAG,"The getNearbyRestaurant latitude is " + latitude + "and the longitude is " +longitude );
        }

        @Override
        public void onKeyExited(String key) {

        }

        @Override
        public void onKeyMoved(String key, GeoLocation location) {

        }

        @Override
        public void onGeoQueryReady() {

        }

        @Override
        public void onGeoQueryError(DatabaseError error) {

        }
    });
}

Моя функция getNearbyRestaurant не вызывается. Я не уверен почему? Я пытался разместить в разных местах, но не смог позвонить. Надеюсь, кто-нибудь может помочь. Я пытаюсь показать список ближайших ресторанов рядом с моим текущим местоположением. Возможно, я что-то упустил. Надеюсь, что кто-нибудь может помочь, так как не хватает ресурсов, когда дело доходит до близлежащих мест. Я видел больше видео по электронной почте

1 Ответ

0 голосов
/ 15 апреля 2020

И fetchLastLocation, и getNearbyRestaurant загружают данные асинхронно. Если вы запустите код в отладчике или добавите несколько журналов, вы увидите, что к моменту запуска GeoQuery geoQuery = geoFire.queryAtLocation(new GeoLocation(latitude,longitude),radius) строки latitude = mCurrentLocation.getLatitude() еще не запускаются.

Данные загружаются из Firebase асинхронно и местоположения извлекаются из ОС Android асинхронно. Основная ветка вашего Android приложения не ждет, когда эти данные или местоположение станут доступными. По этой причине любой код, которому требуется местоположение или данные, должен находиться внутри соответствующего обратного вызова или вызываться оттуда.

Самое простое решение - вызвать getNearbyRestaurant из onSuccess:

Task<Location> task = fusedLocationProviderClient.getLastLocation();
task.addOnSuccessListener(new OnSuccessListener<Location>() {
    @Override
    public void onSuccess(Location location) {
        if (location != null) {

            mCurrentLocation = location;
            Toast.makeText(getApplicationContext(), mCurrentLocation.getLatitude()
                    + "" + mCurrentLocation.getLongitude(), Toast.LENGTH_SHORT).show();
            SupportMapFragment supportMapFragment = (SupportMapFragment)
                    getSupportFragmentManager().findFragmentById(R.id.google_map);
            supportMapFragment.getMapAsync(MapActivity.this);

            latitude = mCurrentLocation.getLatitude();
            longitude = mCurrentLocation.getLongitude();

            Log.d(TAG, "The latitude is " + latitude + " and the longitude is " + longitude);

            getNearbyRestaurant();
        }

Я настоятельно рекомендую читать на асинхронных API, так как это работает практически для любого современного API на основе облака или ввода-вывода.

См .:

...