android - 卫星 map 类型不起作用

标签 android google-maps android-studio google-maps-api-3 google-maps-android-api-2

尊敬的成员(member),我正在开发一个基本的 Google map 应用程序。我已经为这个应用程序实现了一些功能,例如 GPS 检查、互联网检查、工作互联网检查等。我刚刚在顶部添加了一个选项菜单,其中包含一张卫星类型 map 。我已经编写了正确的代码,但每当我单击“卫星”选项来更改 map View 时,应用程序就会自行关闭。终端中没有显示任何错误。应用程序对于所有其他事情都运行良好。我无法弄清楚我在哪里做错了,即关闭我的应用程序而不是加载特定的 map 类型。 以下是我的 main_menu XML 资源文件:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/SatelliteType"
    android:title="@string/satellite"/>
</menu>

下面是Java代码。如果我需要更清楚地阐述这些内容以了解我在此编码实践中的错误/缺点,请告诉我:

package com.example.Test;
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
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;
import java.net.InetAddress;

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
    GoogleMap googleMap;
    private static final int ERROR_DIALOG_REQUEST = 9901;

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


        //****************************Checking the GPS at start*******************
        final LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {

            Toast.makeText(this, "GPS is Enabled in your device", Toast.LENGTH_SHORT).show();
        } else {
            showGPSDisabledAlertToUser();
        }

        //********Checking the Google Play Services at start*********
        if (ServicesOK()) {
            Toast.makeText(this, "CONNECTED to Google Play Services", Toast.LENGTH_SHORT).show();
        }
        //****************************Checking the NETWORKING DEVICE at start*******************
        if (isConnected()) {
            Toast.makeText(this, "CONNECTED to NETWORKING DEVICE", Toast.LENGTH_SHORT).show();
        }
        //****************************Checking the INTERNET SERVICE at Start*******************
        if (isInternetAvailable()) {
            Toast.makeText(this, "CONNECTED to INTERNET", Toast.LENGTH_SHORT).show();
        }

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

    }

    //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    //****************************When MAP is perfectly LOADED*******************
    @Override
    public void onMapReady(GoogleMap googleMap) {
        // Add a marker in CIITLAHORE and move the camera
        LatLng ciitlahore = new LatLng(31.400693, 74.210941);
        googleMap.addMarker(new MarkerOptions().position(ciitlahore).title("Marker in CIIT LAHORE"));
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(ciitlahore));
        googleMap.animateCamera(CameraUpdateFactory.zoomTo(17.0f));
    }

    //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    //****************************Making MENU Option******************

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        //Add menu handling code
        switch (id) {
            case R.id.SatelliteType:
                googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
                return (true);
            default :
                return super.onOptionsItemSelected(item);
        }
    }
    //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    //****************************METHOD for checking GOOGLE PLAY SERVICES*************************
    public boolean ServicesOK() {
        int resultCode = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this);

        if (resultCode == ConnectionResult.SUCCESS) {
            return true;
        } else {
            GoogleApiAvailability.getInstance().getErrorDialog(this, resultCode, ERROR_DIALOG_REQUEST).show();
            Toast.makeText(this, "Can't connect to mapping services", Toast.LENGTH_SHORT).show();
        }
        return false;
    }

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    //****************************METHOD for checking INTERNET AVAILABLE*************************
    public boolean isInternetAvailable() {
        try {
            InetAddress ipAddr = InetAddress.getByName("google.com");
            return !ipAddr.equals("");
        } catch (Exception e) {
            return false;
        }
    }

    //****************************METHOD for checking INTERNET CONNECTIVITY*************************

    public boolean isConnected() {
        ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (activeNetwork != null) {
            // connected to the internet
            if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
                // connected to wifi
                Toast.makeText(this, "WIFI CONNECTION AVAILABLE", Toast.LENGTH_SHORT).show();
            } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
                // connected to the mobile provider's data plan
                Toast.makeText(this, "CELLULAR CONNECTION AVAILABLE", Toast.LENGTH_SHORT).show();
            }
        } else {
            // not connected to the internet
            Toast.makeText(this, "NOT CONNECTED to any working INTERNET service", Toast.LENGTH_SHORT).show();
        }
        return false;
    }

    //****************************GPS DIALOGUE BOX*************************
    private void showGPSDisabledAlertToUser() {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?")
                .setCancelable(false)
                .setPositiveButton("YES",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                Intent callGPSSettingIntent = new Intent(
                                        android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                startActivity(callGPSSettingIntent);
                            }
                        });

        alertDialogBuilder.setNegativeButton("NO",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                        finishAffinity();
                    }
                });
        AlertDialog alert = alertDialogBuilder.create();
        alert.show();
    }
    //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//+++++++++++++++++++++++++++++++++++++++++++  END   +++++++++++++++++++++++++++++++++++++++++++++++
}

最佳答案

您的 googleMap 对象为 null。您需要将其添加到您的 onMapReady 方法中:

this.googleMap = googleMap;

此外,当您选择菜单时,您的 googleMap 对象可能为 null,因此您需要检查它:

if (googleMap != null) {
    googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
}

关于android - 卫星 map 类型不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40400358/

相关文章:

google-maps - 如何将谷歌地图链接到一个div?

java - Android Studio 0.5.4 更新导致 Java.Lang.VerifyError

java - 如何设置时区 UTC+2?

android - 在 Google Play 上退款测试订单

javascript - 谷歌地图标记在拖动后消失

google-maps - map 上带有字母的 Google Map API 标记

java - Iframe Youtube 视频使用 DialogFragment 显示黑屏,并且 Webview 中仅播放音频

android - 未注释的参数覆盖@NonNull 参数

java - 无法加载 JVM DLL - Android Studio

android - 如何使用 Gradle 构建在 Android Studio 中导入 com.google.android.gms.*?