不显示 google api 版本 v2

aks*_*ere 4 android google-maps

运行我的项目后,它显示空白地图,我遵循了很多方法,但仍然显示空白,现在我对地图 api v2 感到困惑,我的控制台不显示所有 api 版本\n这是我的控制台图像,它不显示所有 api 版本

\n\n

这是我的java文件

\n\n
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {\n\nprivate GoogleMap mMap;\nLocationManager locationManager;\nLocationListener locationListener;\n\n@Override\npublic void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {\n    super.onRequestPermissionsResult(requestCode, permissions, grantResults);\n    if(requestCode==1)\n    {\n        if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED)\n        {\n            if(ContextCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED)\n            {\n                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);\n            }\n        }\n    }\n\n}\n\n\n\n@Override\nprotected void onCreate(Bundle savedInstanceState) {\n    super.onCreate(savedInstanceState);\n    setContentView(R.layout.activity_maps);\n    // Obtain the SupportMapFragment and get notified when the map is ready to be used.\n    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()\n            .findFragmentById(R.id.map);\n    mapFragment.getMapAsync(this);\n}\n\n\n/**\n * Manipulates the map once available.\n * This callback is triggered when the map is ready to be used.\n * This is where we can add markers or lines, add listeners or move the camera. In this case,\n * we just add a marker near Sydney, Australia.\n * If Google Play services is not installed on the device, the user will be prompted to install\n * it inside the SupportMapFragment. This method will only be triggered once the user has\n * installed Google Play services and returned to the app.\n */\n@Override\npublic void onMapReady(GoogleMap googleMap) {\n    mMap = googleMap;\n    locationManager=(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);\n    locationListener=new LocationListener() {\n        @Override\n        public void onLocationChanged(Location location) {\n            LatLng myplace = new LatLng(location.getLatitude(),location.getLongitude());\n            mMap.addMarker(new MarkerOptions().position(myplace).title("veraval").icon(BitmapDescriptorFactory.\n                    defaultMarker(BitmapDescriptorFactory.HUE_RED)));\n            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myplace,20));\n\n        }\n\n        @Override\n        public void onStatusChanged(String provider, int status, Bundle extras) {\n\n        }\n\n        @Override\n        public void onProviderEnabled(String provider) {\n\n        }\n\n        @Override\n        public void onProviderDisabled(String provider) {\n\n        }\n    };\n\n\n        if (ContextCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {\n\n            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);\n        } else {\n            Toast.makeText(MapsActivity.this,"hello",Toast.LENGTH_LONG).show();\n\n            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);\n\n        }\n\n\n\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

这是我的 build.gradle 文件,我已经添加了所有依赖项,但它仍然显示空白地图

\n\n
android {\ncompileSdkVersion 27\ndefaultConfig {\n    applicationId "com.example.user.mapexample"\n    minSdkVersion 19\n    targetSdkVersion 27\n    versionCode 1\n    versionName "1.0"\n    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"\n}\nbuildTypes {\n    release {\n        minifyEnabled false\n        proguardFiles getDefaultProguardFile(\'proguard-android.txt\'), \'proguard-rules.pro\'\n        resValue "string", "google_maps_api_key", "Release_API_KEY"\n\n    }\n    debug{\n        resValue "string", "google_maps_api_key", "DEBUG_API_KEY"\n    } \ndependencies {\nimplementation fileTree(dir: \'libs\', include: [\'*.jar\'])\nimplementation \'com.android.support:appcompat-v7:27.1.1\'\nimplementation \'com.android.support:support-v4:27.1.1\'\nimplementation \'com.android.support:support-media-compat:27.1.1\'\nimplementation \'com.google.android.gms:play-services-maps:15.0.1\'\ntestImplementation \'junit:junit:4.12\'\nandroidTestImplementation \'com.android.support.test:runner:0.5\'\nandroidTestImplementation \'com.android.support.test.espresso:espresso-core:3.0.2\'\n
Run Code Online (Sandbox Code Playgroud)\n\n

这是我的日志猫

\n\n
07-26 12:14:12.046 7855-7855/? I/art: Late-enabling -Xcheck:jni\n07-26 12:14:12.071 7855-7862/? I/art: Debugger is no longer active\n07-26 12:14:12.071 7855-7862/? I/art: Starting a blocking GC Instrumentation\n07-26 12:14:12.204 7855-7855/? D/LenovoAppIconTheme: \nExtraResources;cleanCachedIcon;clear cache..\n07-26 12:14:12.210 7855-7855/? W/System: ClassLoader referenced unknown path: \n/data/app/com.example.user.mapsexample-1/lib/arm\n07-26 12:14:12.338 7855-7855/? I/zzbz: Making Creator dynamically\n07-26 12:14:12.380 7855-7855/? I/DynamiteModule: Considering local module \ncom.google.android.gms.maps_dynamite:0 and remote module \ncom.google.android.gms.maps_dynamite:220\n07-26 12:14:12.380 7855-7855/? I/DynamiteModule: Selected remote version of \ncom.google.android.gms.maps_dynamite, version >= 220\n07-26 12:14:12.404 7855-7855/? W/System: ClassLoader referenced unknown path: \n07-26 12:14:12.518 7855-7855/? I/Google\xc2\xa0Maps\xc2\xa0Android\xc2\xa0API: Google Play \nservices client version: 12451000\n07-26 12:14:12.540 7855-7855/? I/Google\xc2\xa0Maps\xc2\xa0Android\xc2\xa0API: Google Play \nservices package version: 12874022\n07-26 12:14:13.312 7855-7855/com.example.user.mapsexample E/art: The \nString#value field is not present on Android versions >= 6.0\n07-26 12:14:13.690 7855-7901/com.example.user.mapsexample \nD/NetworkSecurityConfig: No Network Security Config specified, using platform \ndefault\n07-26 12:14:13.709 7855-7901/com.example.user.mapsexample I/DpmTcmClient: \nRegisterTcmMonitor from: com.android.okhttp.TcmIdleTimerMonitor\n07-26 12:14:13.930 7855-7936/com.example.user.mapsexample I/Adreno: QUALCOMM \nbuild                   : 5817cca, Ie9c95840c4\n                                                                Build Date                       \n: 03/26/17\n                                                                OpenGL ES \nShader Compiler Version: XE031.09.00.03\n                                                                Local Branch                     \n: \n                                                                Remote Branch                    \n: refs/tags/AU_LINUX_ANDROID_LA.UM.5.5.R1.07.00.00.269.021\n                                                                Remote Branch                    \n: NONE\n                                                                Reconstruct \nBranch               : NOTHING\n07-26 12:14:13.956 7855-7936/com.example.user.mapsexample I/OpenGLRenderer: \nInitialized EGL, version 1.4\n07-26 12:14:13.957 7855-7936/com.example.user.mapsexample D/OpenGLRenderer: \nSwap behavior 1\n07-26 12:14:14.258 7855-7866/com.example.user.mapsexample W/art: Suspending \nall \nthreads took: 18.013ms\n07-26 12:14:14.287 7855-7866/com.example.user.mapsexample I/art: Background \nsticky concurrent mark sweep GC freed 7913(862KB) AllocSpace objects, \n20(1612KB) LOS objects, 0% free, 13MB/13MB, paused 20.215ms total 77.392ms\n07-26 12:14:14.743 7855-7866/com.example.user.mapsexample I/art: Background \nsticky concurrent mark sweep GC freed 4729(195KB) AllocSpace objects, 4(2MB) \nLOS objects, 9% free, 25MB/28MB, paused 5.557ms total 19.833ms\n07-26 12:14:16.187 7855-7934/com.example.user.mapsexample W/DynamiteModule: \nLocal module descriptor class for com.google.android.gms.googlecertificates \nnot found.\n07-26 12:14:16.199 7855-7934/com.example.user.mapsexample I/DynamiteModule: \nConsidering local module com.google.android.gms.googlecertificates:0 and \nremote module com.google.android.gms.googlecertificates:4\n07-26 12:14:16.199 7855-7934/com.example.user.mapsexample I/DynamiteModule: \nSelected remote version of com.google.android.gms.googlecertificates, version \n>= 4\n
Run Code Online (Sandbox Code Playgroud)\n\n

这是我在物理设备中得到的输出

\n

Kha*_*ela 6

构建.gradle

buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            resValue "string", "google_maps_api_key", "Release_API_KEY"
        }
        debug {
//          KL MBP debug Key
            resValue "string", "google_maps_api_key", "DEBUG_API_KEY"
//          KL Old Machine debug Key
//            resValue "string", "google_maps_api_key", "DEBUG_API_KEY"
        }
    }
Run Code Online (Sandbox Code Playgroud)

AndroidManifest.xml

<meta-data
    android:name="com.google.android.maps.v2.API_KEY"
    android:value="@string/google_maps_api_key"/>

<uses-library
    android:name="com.google.android.maps"
    android:required="true" />
Run Code Online (Sandbox Code Playgroud)

检查我的答案,了解有关如何设置 API 密钥google_maps_api_key并添加为发布或调试的更多详细信息build.gradle

更新1

  • 设置 Google 地图 API 密钥的简单方法。

  • 要获取一个,请点击此链接,按照说明进行操作,然后按最后的“创建”:

    https://console.developers.google.com/flows/enableapi?apiid=maps_android_backend&keyType=CLIENT_SIDE_ANDROID&r={SHA-1}%3B{YOUR_APP_PACKAGE_NAME}

    • 前任:

      https://console.developers.google.com/flows/enableapi?apiid=maps_android_backend&keyType=CLIENT_SIDE_ANDROID&r=08:F2:4F:C5:43:3E:4E:B7:30:71:0F:06:F1:9F:85:F5:E2:1D:B8:73%3Bcom.lelasoft.googlemapv2

注意:设置最多可能需要 5 分钟才能生效

更新2

  • 我创建了新的,在使用更新 1MapActivity指令设置 API 密钥后它可以与我一起使用,大约需要 5 分钟才能生效

更新3

  • 设置 Android 模拟器地理位置

在此输入图像描述

更新4

  • 要求用户在设备上启用GeoLocation

构建.gradle

dependencies {
     // Other dependences 
    implementation 'com.google.android.gms:play-services-location:15.0.1' // add location dependency.
    implementation 'com.google.android.gms:play-services-maps:15.0.1'
}
Run Code Online (Sandbox Code Playgroud)

地图活动.java

@Override
public void onMapReady(GoogleMap googleMap) {
    this.googleMap = googleMap;
    buildGoogleApiClient();
    googleApiClient.connect();
}

protected synchronized void buildGoogleApiClient() {
    googleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
}

@Override
public void onLocationChanged(Location location) {
    googleMap.clear();
    LatLng myplace = new LatLng(location.getLatitude(), location.getLongitude());

    // Add a marker in Sydney and move the camera
    googleMap.addMarker(new MarkerOptions().position(myplace).title("Marker in My Current Location"));
    googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myplace,17));
}

/**
 * Enables the My Location layer if the fine mLocation permission has been granted.
 */
private void enableMyLocation() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN
            && ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_ACCESS_FINE_LOCATION_PERMISSION);
    }else if (googleApiClient != null && locationRequest !=null){
        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
        googleMap.setMyLocationEnabled(true);
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                       @NonNull int[] grantResults) {
    switch (requestCode) {
        case REQUEST_ACCESS_FINE_LOCATION_PERMISSION:
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                enableMyLocation();
            }
            break;
        default:
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_ACCESS_FINE_LOCATION_PERMISSION){
        enableMyLocation();
    }
}


@Override
public void onResume() {
    super.onResume();
    if (googleApiClient !=null)
        createLocationRequest();
}


protected void createLocationRequest() {
    locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(30 * 1000);
    locationRequest.setFastestInterval(5 * 1000);
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
            .addLocationRequest(locationRequest);
    //**************************
    builder.setAlwaysShow(true); //this is the key ingredient
    //**************************
    PendingResult<LocationSettingsResult> result =
            LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
    result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
        @Override
        public void onResult(@NonNull LocationSettingsResult result) {
            final Status status = result.getStatus();
            final LocationSettingsStates state = result.getLocationSettingsStates();
            switch (status.getStatusCode()) {
                case LocationSettingsStatusCodes.SUCCESS:
                    // All mLocation settings are satisfied. The client can initialize mLocation
                    // requests here.
                    enableMyLocation();
                    break;
                case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                    // Location settings are not satisfied. But could be fixed by showing the user
                    // a dialog.
                    try {
                        // Show the dialog by calling startResolutionForResult(),
                        // and check the result in onActivityResult().
                        status.startResolutionForResult(MapsActivity.this, REQUEST_ACCESS_FINE_LOCATION_PERMISSION);
                    } catch (IntentSender.SendIntentException e) {
                        // Ignore the error.
                    }
                    break;
                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                    // Location settings are not satisfied. However, we have no way to fix the
                    // settings so we won't show the dialog.
                    break;
            }
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

检查完整的Github 示例

  • 兄弟,你刚刚震撼了它,非常感谢你的宝贵回答,我已经搜索了三天了 (2认同)