如何在Android上的GoogleMap中修复com.google.android.gms.maps.model.Ma



我想在我的应用程序中使用GoogleMap。 对于创建GoogleMap,我使用此补丁:新的 -> 谷歌 ->谷歌地图活动,我写下面的代码,但在运行时显示强制关闭错误。
地图活动代码:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
    private GoogleMap mMap;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // 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);
        setUpMap();
    }

    /**
     * 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) {
        mMap = googleMap;
        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
    private void setUpMap() {
        mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker").snippet("Snippet"));
        // Enable MyLocation Layer of Google Map
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        mMap.setMyLocationEnabled(true);
        // Get LocationManager object from System Service LOCATION_SERVICE
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        // Create a criteria object to retrieve provider
        Criteria criteria = new Criteria();
        // Get the name of the best provider
        String provider = locationManager.getBestProvider(criteria, true);
        // Get Current Location
        Location myLocation = locationManager.getLastKnownLocation(provider);
        // set map type
        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        // Get latitude of the current location
        double latitude = myLocation.getLatitude();
        // Get longitude of the current location
        double longitude = myLocation.getLongitude();
        // Create a LatLng object for the current location
        LatLng latLng = new LatLng(latitude, longitude);
        // Show the current location in Google Map
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        // Zoom in the Google Map
        mMap.animateCamera(CameraUpdateFactory.zoomTo(14));
        mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("You are here!").snippet("Consider yourself located"));
    }
}

XML代码:

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    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="com.tellfa.googlepluslogin.map.MapsActivity" />

日志猫错误:

05-21 17:34:45.173 31057-31057/com.tellfa.googlepluslogin E/AndroidRuntime: FATAL EXCEPTION: main
                                                                            Process: com.tellfa.googlepluslogin, PID: 31057
                                                                            java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tellfa.googlepluslogin/com.tellfa.googlepluslogin.map.MapsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2331)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
                                                                                at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1309)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5349)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
                                                                             Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference
                                                                                at com.tellfa.googlepluslogin.map.MapsActivity.setUpMap(MapsActivity.java:58)
                                                                                at com.tellfa.googlepluslogin.map.MapsActivity.onCreate(MapsActivity.java:34)
                                                                                at android.app.Activity.performCreate(Activity.java:6020)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2284)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391) 
                                                                                at android.app.ActivityThread.access$800(ActivityThread.java:151) 
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1309) 
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                                at android.os.Looper.loop(Looper.java:135) 
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5349) 
                                                                                at java.lang.reflect.Method.invoke(Native Method) 
                                                                                at java.lang.reflect.Method.invoke(Method.java:372) 
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908) 
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703) 
05-21 17:34:47.180 31057-31255/com.tellfa.googlepluslogin E/DynamiteModule: Failed to load module descriptor class: Didn't find class "com.google.android.gms.dynamite.descriptors.com.google.android.gms.googlecertificates.ModuleDescriptor" on path: DexPathList[[zip file "/data/app/com.tellfa.googlepluslogin-1/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]

如何解决此问题?

mMap 为空,因为您从 onCreate() 调用setUpMap(),但目前 map 尚未初始化。它将在onMapReady()方法中初始化。

您应该setUpMap()呼叫移动到onMapReady()

我对此了解不多,但我认为您的错误在于这一行:

mMap.addMarker(new MarkerOptions().position(new LatLng(0,       0)).title("Marker").snippet("Snippet"));

mMap 需要先初始化,然后你可以给它添加标记,尝试在 onMapReady() 中调用 setUpMap()。

遵循我目前使用的这些片段。

public class MyActivity extends FragmentActivity implements LocationListener {
    GoogleMap googleMap;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //show error dialog if GoolglePlayServices not available
        if (!isGooglePlayServicesAvailable()) {
            finish();
        }
        setContentView(R.layout.activity_my);
        SupportMapFragment supportMapFragment =
                (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap);
        googleMap = supportMapFragment.getMap();
        googleMap.setMyLocationEnabled(true);
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String bestProvider = locationManager.getBestProvider(criteria, true);
        Location location = locationManager.getLastKnownLocation(bestProvider);
        if (location != null) {
            onLocationChanged(location);
        }
        locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);
    }
    @Override
    public void onLocationChanged(Location location) {
        TextView locationTv = (TextView) findViewById(R.id.latlongLocation);
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
        LatLng latLng = new LatLng(latitude, longitude);
        googleMap.addMarker(new MarkerOptions().position(latLng));
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
        locationTv.setText("Latitude:" + latitude + ", Longitude:" + longitude);
    }
    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
    }
    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
    }
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
    }
    private boolean isGooglePlayServicesAvailable() {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (ConnectionResult.SUCCESS == status) {
            return true;
        } else {
            GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
            return false;
        }
    }
}

.XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <fragment
        android:id="@+id/googleMap"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.SupportMapFragment"
        android:layout_above="@+id/latlongLocation" />
    <TextView
        android:id="@+id/latlongLocation"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="bottom"
        android:layout_alignParentBottom="true"
        android:background="#ff058fff"
        android:paddingTop="5dp"
        android:paddingBottom="5dp"
        android:textColor="#ffffffff"
        android:paddingLeft="5dp"
        android:paddingRight="5dp" />
</RelativeLayout>

您需要Manifest的许可是。

 <uses-permission android:name="com.javapapers.currentlocationinmap.permission.MAPS_RECEIVE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

注意:应用运行时权限以及您在OP中使用的权限。

private void setUpMap() {
-->     mMap=googleMap;
        mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker").snippet("Snippet"));

最新更新