【问题标题】:Android - Cannot initialize Google PlacesAndroid - 无法初始化 Google 地方信息
【发布时间】:2019-04-20 04:59:47
【问题描述】:

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

我正在尝试使用 Google 地点自动完成小部件进行搜索,然后返回地图的地址位置。尝试初始化 Google 地方信息时出现错误 Cannot resolve symbol 'initialize'

这是我的代码:

地图活动

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

【问题讨论】:

  • YOUR_API_KEY 在哪里?
  • 没有。即使我确实在那里放置了一个,它也不起作用。函数 initialize 未被识别为有效函数。 Intellisense 完全忽略它。我试图使缓存无效并重新启动。它发生在我的 Windows PC 和 Macbook 上。
  • Places.initialize(context, "GOOGLE_ANDROID_API_KEY");你需要先调用place init方法。

标签: java android firebase google-maps


【解决方案1】:

你在这里犯了一个非常愚蠢的错误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 覆盖方法中创建活动时初始化库

【讨论】:

  • 感觉像这样的旋钮。多谢了。补充问题:在代码中存储实际 api 密钥的最佳位置在哪里,因此不会上传到 Github 等。
  • 不用担心,感谢您接受我的回答。 android包中没有安全存储api key的地方,上传到github时最好不要在任何地方添加api key。或者你可以在上传到github时加密api密钥并添加到txt文件中
猜你喜欢
  • 1970-01-01
  • 2011-05-08
  • 1970-01-01
  • 1970-01-01
  • 2017-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多