getMapAsync()不起作用

时间:2017-05-27 04:28:48

标签: android google-maps nullpointerexception

使用var array = ["A": [FruitsData(name: "apple", id: "5"), FruitsData(name: "apricot",id: "")], "M": [FruitsData(name: "mango", id: "9"), FruitsData(name: "grapes", id: "")]] 时使用回调时收到错误,因为getMapAsync()已弃用。有关如何更新此代码的任何想法,以便不会抛出错误?拉入getMap()以定位地图上的图钉

API

05-26 22:50:13.419 12576-12576/com.example.kdotz.zoo E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.kdotz.zoo, PID: 12576 java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.animateCamera(com.goog‌​le.android.gms.maps.‌​CameraUpdate, com.google.android.gms.maps.GoogleMap$CancelableCallback)' on a null object reference

1 个答案:

答案 0 :(得分:1)

您应该只调用getMapAsync()一次,当地图准备好后,onMapReady()回调会为您提供Google地图参考。然后,您可以根据需要操作GoogleMap。

另请注意,由于ZooMapFragment扩展了SupportMapFragment,因此无需使用onViewCreated(),您只需使用onResume()覆盖。

public class ZooMapFragment extends SupportMapFragment 
        implements OnMapReadyCallback {

    private GoogleMap mMap;

    public ZooMapFragment() {
    }

    @Override
    public void onResume() {
        super.onResume();

        setUpMapIfNeeded();

        //Other stuff:
        RestAdapter adapter = new RestAdapter.Builder()
          .setEndpoint(getString(R.string.pins_feed))
          .build();

        PinsApiInterface pinsApiInterface = adapter.create(PinsApiInterface.class);

        pinsApiInterface.getStreams(new Callback<List<Pin>>() {
            @Override
            public void success(List<Pin> pins, Response response) {
                for(Pin pin: pins){
                    Log.e("Zoo", pin.getName());
                }
            }
    }

    private void setUpMapIfNeeded() {
        if (mMap == null) {
            getMapAsync(this);
        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        mMap.setMyLocationEnabled(true);
        mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
        mMap.getUiSettings().setMapToolbarEnabled(false);


        mMap.setOnMarkerClickListener( new GoogleMap.OnMarkerClickListener() {
          @Override
          public boolean onMarkerClick(Marker marker) {
            marker.showInfoWindow();
            return true;
          }
        });

         // Add a marker in Denver, Zoo
        // and move the map's camera to the same location.
        LatLng denverZoo = new LatLng(39.7500, -104.9500);
        mMap.addMarker(new MarkerOptions().position(denverZoo)
                .title("Marker in Denver Zoo"));
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(denverZoo, 15));
    }
}