java - Android - 无法初始化 Google 地方信息

标签 java android firebase google-maps

我有一个应用结合使用了 Google map 、地点和 Firebase。

我正在尝试使用 Google 地点自动完成小部件来搜索,然后返回 map 的地址位置。尝试初始化 Google 商家信息时出现错误无法解析符号“initialize”

这是我的代码:

map Activity

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 文档的说明(我认为)。我不确定我哪里出错了。

最佳答案

你在这里犯了一个非常愚蠢的错误 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);
}

原因如下......

创建 Activity 时库会被初始化,这是在 onCreate 重写方法中完成的

关于java - Android - 无法初始化 Google 地方信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55770406/

相关文章:

java - 如何在 cocos2d android 1 中创建 cocos2d 粒子效果?

javascript - 连接 firebase 阵列?

java - Spring REST 3 支持 XML 和 JSON

java - Android 中 Java 的自动点击 html 按钮

java - 创建与子类相同类型的对象

android - Bouncy CaSTLe Keystore (BKS) : java. io.IOException: keystore 版本错误

android - 运行错误 'sbt start-device'

ios - Firebase云函数始终响应代码=-1001 "The request timed out."

javascript - Firestore - 无法编码值 - 使用 Promise.all() 和 MongoDB Insert 添加文档时

java - 如何 javax.mail.AuthenticationFailedException : failed to connect in sending mail by java?