2016-08-15 74 views
1

我試圖開發Android應用程序與谷歌地圖,但我有錯誤 -的Android CameraUpdateFactory未初始化

NullPointerException異常:CameraUpdateFactory未初始化

GoogleMap mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap(); 

    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); 


    Criteria criteria = new Criteria(); 


    String provider = locationManager.getBestProvider(criteria, true); 
    Location location = locationManager.getLastKnownLocation(provider); 
    locationManager.requestLocationUpdates(provider, 20000, 0, this);  

    double lat = Double.parseDouble("xx.xxxxxx"); 
    double log = Double.parseDouble("yy.yyyyyy"); 
    LatLng currentPosition = new LatLng(lat, log); 

    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentPosition,16)); 
    mMap.addMarker(new MarkerOptions() 
      .position(currentPosition) 
      .snippet("Lat:" + lat + "Lng:" + log)); 

請幫助我。 在此先感謝。

回答

1

你需要實現

OnMapReadyCallback

,然後覆蓋

onMapReady

這是爲了確保您的地圖已正確設置,並準備任何相機更新。

public class YourMapFragment extends Fragment implements OnMapReadyCallback { 
... 
@Override 
public void onMapReady(GoogleMap googleMap) { 
mMap = googleMap; 
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentPosition,16)); 

    mMap.addMarker(new MarkerOptions() 
      .position(currentPosition) 
      .snippet("Lat:" + lat + "Lng:" + log)); 
} 

    ... 
    }