Android - не удается инициализировать Google Места на карте - PullRequest
0 голосов
/ 20 апреля 2019

У меня есть приложение, которое использует комбинацию Google Maps, Places и Firebase.

Я пытаюсь использовать виджет автозаполнения мест Google для поиска, а затем возврата местоположений адресов для карты. При попытке инициализации Google Адресов я получаю сообщение об ошибке Cannot resolve symbol 'initialize'

Вот мой код:

MapsActivity

package com.k99studio.firemap;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.libraries.places.api.Places;
import com.google.android.libraries.places.api.model.RectangularBounds;
import com.google.android.libraries.places.api.model.TypeFilter;
import com.google.android.libraries.places.api.net.PlacesClient;
import com.google.android.libraries.places.widget.Autocomplete;
import com.google.android.libraries.places.widget.model.AutocompleteActivityMode;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    private FirebaseAuth fbAuth;
    private FirebaseUser fbUser;
    private FirebaseAuth.AuthStateListener authStateListener;

    Places.initialize(getApplicationContext(), YOUR_API_KEY);
    PlacesClient placesClient = Places.createClient(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        // Loads the actionbar with custom menu maps_menu.xml
        getSupportActionBar();

        // Creates a listener than monitors the state of the firebase authentication.  If the state
        // of the authentication changes at any point during the app usage then the function will be
        // called.  If there is found to be no current user (logged out, token expired etc.) then
        // the user will be redirected to the sign in (Auth) activity.
        fbAuth = FirebaseAuth.getInstance();
        fbUser = FirebaseAuth.getInstance().getCurrentUser();
        authStateListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                if (fbUser == null){
                    startActivity(new Intent(MapsActivity.this, AuthActivity.class));
                    finish();
                }
            }
        };

        // 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
    protected void onStart() {
        super.onStart();
        // Starts the authentication listener
        fbAuth.addAuthStateListener(authStateListener);
    }

    @Override
    protected void onStop() {
        super.onStop();
        // Stops the authentication listener.
        if (authStateListener != null) {
            fbAuth.removeAuthStateListener(authStateListener);
        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Set default map location to Milton Fire Station
        LatLng miltonFireStation = new LatLng(-46.120031, 169.958416);
        mMap.moveCamera(CameraUpdateFactory.newLatLng(miltonFireStation));
        mMap.moveCamera(CameraUpdateFactory.zoomTo(15.0f));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflates the custom menu options on to the action bar
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.maps_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handles button presses for buttons on the action bar and action bar menu
        switch (item.getItemId()) {
            case R.id.newMarker:
                // New marker.  Go to the new marker activity
                startActivity(new Intent(MapsActivity.this, CreateActivity.class));
                return true;

            case R.id.searchAddress:
                // Search button is pressed.  Start the google places auto complete search
                startAutocompleteActivity();
                return true;

            case R.id.mapStandard:
                //  Set google map type to Normal
                mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                return true;

            case R.id.mapSatellite:
                // Set google map type to Satellite
                mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
                return true;

            case R.id.mapHybrid:
                // Set google map type to Hybrid
                mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
                return true;

            case R.id.logOut:
                // Signs the users our of firebase authentication.  Should trigger the AuthStateListener
                // to return the user to the Auth Activity.
                fbAuth.signOut();
                return true;

            default:
                // If we got here, the user's action was not recognized.
                // Invoke the superclass to handle it.
                return super.onOptionsItemSelected(item);

        }
    }

    private void startAutocompleteActivity() {
        // Auto complete search widget for google places.  To get address coordinates to return to the map location.
        List<com.google.android.libraries.places.api.model.Place.Field> placeFields = new ArrayList<>(Arrays.asList(com.google.android.libraries.places.api.model.Place.Field.values()));
        List<TypeFilter> typeFilters = new ArrayList<>(Arrays.asList(TypeFilter.values()));
        // Create a RectangularBounds object.
        RectangularBounds bounds = RectangularBounds.newInstance(
                new LatLng(-33.880490, 151.184363),
                new LatLng(-33.858754, 151.229596));
        Intent autocompleteIntent =
                new Autocomplete.IntentBuilder(AutocompleteActivityMode.FULLSCREEN, placeFields)
                        .setLocationBias(bounds)
                        .setTypeFilter(typeFilters.get(0))
                        .build(this);
        startActivityForResult(autocompleteIntent, 1001);
    }
}

Мои зависимости настроены следующим образом:

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    //noinspection GradleCompatible
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.google.android.gms:play-services-maps:16.1.0'
    implementation "com.google.android.libraries.places:places:1.1.0"
    implementation 'com.google.firebase:firebase-auth:16.2.1'
    implementation 'com.google.firebase:firebase-firestore:18.2.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
}

Я немного сбит с толку этим, так как я следовал инструкциям из документов Google (я думаю). Я не уверен, где я ошибся.

1 Ответ

2 голосов
/ 20 апреля 2019

Вы допустили очень глупую ошибку. Функция places.initialize() должна быть частью onCreate и не быть объявлена ​​глобально. Ваш код станет ..

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
Places.initialize(getApplicationContext(), YOUR_API_KEY);
    PlacesClient placesClient = Places.createClient(this);

        // Loads the actionbar with custom menu maps_menu.xml
        getSupportActionBar();

        // Creates a listener than monitors the state of the firebase authentication.  If the state
        // of the authentication changes at any point during the app usage then the function will be
        // called.  If there is found to be no current user (logged out, token expired etc.) then
        // the user will be redirected to the sign in (Auth) activity.
        fbAuth = FirebaseAuth.getInstance();
        fbUser = FirebaseAuth.getInstance().getCurrentUser();
        authStateListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                if (fbUser == null){
                    startActivity(new Intent(MapsActivity.this, AuthActivity.class));
                    finish();
                }
            }
        };

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

Вот почему .....

Библиотека инициализируется при создании операции, которая выполняется методом переопределения onCreate

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...