为什么Google Maps Fragment在Android应用程序中为空白

如何解决为什么Google Maps Fragment在Android应用程序中为空白

我是Android开发的新手。我在底部导航中添加了Google Maps Fragment,还添加了api键。但是,当我在应用程序中打开地图片段时,它会显示空白地图。

我已经将Android Studio的默认代码用于Google Maps Fragment和底部导航,但是我不知道为什么会遇到这个问题。

我曾在不同的设备上尝试过此操作,但仍然遇到相同的问题

这是我的代码

MapsFragment.java

package com.avvaldeveloper.mapfrag.ui.map;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;

import com.avvaldeveloper.mapfrag.R;
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.gms.maps.model.MarkerOptions;

public class MapsFragment extends Fragment {

    public static final int REQUEST_LOCATION_CODE = 99;
    private OnMapReadyCallback callback = new OnMapReadyCallback() {

        /**
         * Manipulates the map once available.
         * This callback is triggered when the map is ready to be used.
         * This is where we can add markers or lines,add listeners or move the camera.
         * In this case,we just add a marker near Sydney,Australia.
         * If Google Play services is not installed on the device,the user will be prompted to
         * install it inside the SupportMapFragment. This method will only be triggered once the
         * user has installed Google Play services and returned to the app.
         */
        @Override
        public void onMapReady(GoogleMap googleMap) {

            LatLng sydney = new LatLng(-34,151);
            googleMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
            googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));

            if (ActivityCompat.checkSelfPermission(getActivity(),Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(),Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //code for permission not granted.
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_LOCATION_CODE);
                }
            } else {

                Toast.makeText(getActivity(),"Loading",Toast.LENGTH_LONG).show();

            }

        }
    };

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,@Nullable ViewGroup container,@Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_maps,container,false);
    }

    @Override
    public void onViewCreated(@NonNull View view,@Nullable Bundle savedInstanceState) {
        super.onViewCreated(view,savedInstanceState);
        SupportMapFragment mapFragment =
                (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
        if (mapFragment != null) {
            mapFragment.getMapAsync(callback);

        }
    }
}

fragment_maps.xml

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.map.MapsFragment" />

依赖项

implementation fileTree(dir: "libs",include: ["*.jar"])
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.google.android.material:material:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.vectordrawable:vectordrawable:1.1.0'
    implementation 'androidx.navigation:navigation-fragment:2.3.0'
    implementation 'androidx.navigation:navigation-ui:2.3.0'
    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
    implementation 'com.google.android.gms:play-services-maps:17.0.0'
    implementation 'com.google.android.gms:play-services-location:17.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.avvaldeveloper.mapfrag">

    <!--
         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2,but you must specify either coarse or fine
         location permissions for the "MyLocation" functionality.
    -->
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key,including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/.
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity
            android:name=".MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

MainActivity.java

package com.avvaldeveloper.mapfrag;

import android.os.Bundle;

import com.google.android.material.bottomnavigation.BottomNavigationView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BottomNavigationView navView = findViewById(R.id.nav_view);
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
                R.id.navigation_home,R.id.navigation_dashboard,R.id.navigation_notifications,R.id.navigation_map)
                .build();
        NavController navController = Navigation.findNavController(this,R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this,navController,appBarConfiguration);
        NavigationUI.setupWithNavController(navView,navController);
    }

}

Logcat

2020-08-15 12:14:50.048 1434-2751/? W/audio_hw_generic: Not supplying enough data to HAL,expected position 17727575,only wrote 17727120
2020-08-15 12:14:50.169 13447-13447/com.avvaldeveloper.mapfrag I/Google Maps Android API: Google Play services package version: 200414022
2020-08-15 12:14:50.560 13447-13715/com.avvaldeveloper.mapfrag D/EGL_emulation: eglCreateContext: 0xe0e86fe0: maj 1 min 0 rcv 1
2020-08-15 12:14:50.560 1442-1442/? D/gralloc_ranchu: gralloc_alloc: Creating ashmem region of size 7344128
2020-08-15 12:14:50.568 1838-1866/system_process E/memtrack: Couldn't load memtrack module
2020-08-15 12:14:50.568 1838-1866/system_process W/android.os.Debug: failed to get memory consumption info: -1
2020-08-15 12:14:50.611 1838-5693/system_process I/GnssLocationProvider: WakeLock acquired by sendMessage(SET_REQUEST,com.android.server.location.GnssLocationProvider$GpsRequest@670f1d3)
2020-08-15 12:14:50.618 1838-1866/system_process I/GnssLocationProvider: WakeLock released by handleMessage(SET_REQUEST,com.android.server.location.GnssLocationProvider$GpsRequest@670f1d3)
2020-08-15 12:14:50.632 13447-13715/com.avvaldeveloper.mapfrag D/EGL_emulation: eglMakeCurrent: 0xe0e86fe0: ver 1 0 (tinfo 0xe0e83d50)
2020-08-15 12:14:50.775 2460-13658/com.google.android.gms.persistent I/GCoreUlr: Successfully inserted 1 locations
2020-08-15 12:14:50.868 1442-1442/? D/gralloc_ranchu: gralloc_alloc: Creating ashmem region of size 122880
2020-08-15 12:14:50.875 1442-1442/? D/gralloc_ranchu: gralloc_alloc: Creating ashmem region of size 122880
2020-08-15 12:14:50.881 1442-1536/? D/gralloc_ranchu: gralloc_alloc: Creating ashmem region of size 122880
2020-08-15 12:14:50.916 13447-13481/com.avvaldeveloper.mapfrag D/EGL_emulation: eglMakeCurrent: 0xe0e850c0: ver 3 1 (tinfo 0xe0e832f0)
2020-08-15 12:14:50.943 13447-13481/com.avvaldeveloper.mapfrag D/EGL_emulation: eglMakeCurrent: 0xe0e850c0: ver 3 1 (tinfo 0xe0e832f0)
2020-08-15 12:14:50.957 1442-1536/? D/gralloc_ranchu: gralloc_alloc: Creating ashmem region of size 7344128
2020-08-15 12:14:51.013 1442-1536/? D/gralloc_ranchu: gralloc_alloc: Creating ashmem region of size 7344128
2020-08-15 12:14:53.290 1434-1434/? W/audio_hw_generic: Not supplying enough data to HAL,expected position 18036652,only wrote 17882640
2020-08-15 12:14:54.091 1838-1838/system_process W/WindowManager: removeWindowToken: Attempted to remove non-existing token: android.os.Binder@b160ea4
2020-08-15 12:14:54.095 1452-1988/? D/gralloc_ranchu: gralloc_unregister_buffer: exiting HostConnection (is buffer-handling thread)
2020-08-15 12:14:54.098 1452-1988/? D/gralloc_ranchu: gralloc_unregister_buffer: exiting HostConnection (is buffer-handling thread)
2020-08-15 12:14:54.103 1452-1988/? D/gralloc_ranchu: gralloc_unregister_buffer: exiting HostConnection (is buffer-handling thread)
2020-08-15 12:14:54.107 1452-1988/? D/gralloc_ranchu: gralloc_unregister_buffer: exiting HostConnection (is buffer-handling thread)
2020-08-15 12:14:54.644 1443-1443/? D/gralloc_ranchu: gralloc_unregister_buffer: exiting HostConnection (is buffer-handling thread)
2020-08-15 12:14:54.645 1443-1443/? D/gralloc_ranchu: gralloc_unregister_buffer: exiting HostConnection (is buffer-handling thread)
2020-08-15 12:14:59.291 1450-1450/? I/boot-pipe: done populating /dev/random
2020-08-15 12:15:06.020 2460-13658/com.google.android.gms.persistent I/GCoreUlr: Successfully inserted 1 locations
2020-08-15 12:15:06.113 1838-1848/system_process I/zygote: Background concurrent copying GC freed 14909(1034KB) AllocSpace objects,0(0B) LOS objects,36% free,10MB/16MB,paused 3.384ms total 205.409ms
2020-08-15 12:15:08.879 1838-1872/system_process E/BatteryExternalStatsWorker: modem info is invalid: ModemActivityInfo{ mTimestamp=0 mSleepTimeMs=0 mIdleTimeMs=0 mTxTimeMs[]=[0,0] mRxTimeMs=0 mEnergyUsed=0}
2020-08-15 12:15:21.082 2460-13402/com.google.android.gms.persistent I/GCoreUlr: Successfully inserted 1 locations

显示错误

2020-08-15 12:17:12.792 1838-1866/system_process E/memtrack: Couldn't load memtrack module

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-