2016-03-17 29 views
1

我試圖獲取當前位置並在地圖上用當前位置設置標記。爲了查看應用程序是否正在檢索經緯度,我把這個Toast放在了一起,而Toast的工作是完美的。唯一的問題是在addMarker和moveCamera上,兩者都在logcat上顯示相同的錯誤。Google地圖試圖調用com.google.android.gms.maps.model.Marker的錯誤

有人可以幫我嗎?我還沒有發現在谷歌的錯誤的任何解釋(不是NullPointException,我已經找到了很多這一個)

這裏的MapsActivty:

public GoogleMap mMap; 
double latitude = 0; 
double longitude = 0; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_maps); 
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() 
      .findFragmentById(R.id.map); 

    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 

    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, (LocationListener) this); 
} 

public void onLocationChanged(Location location) { 
    // TODO Auto-generated method stub 

    latitude = location.getLatitude(); 
    longitude = location.getLongitude(); 

    String text = "Geo_Location \nLatitude: " + latitude + "\nLongitude: " + longitude; 
    Toast.makeText(this, text, Toast.LENGTH_LONG).show(); 

    LatLng myLocation = new LatLng(location.getLatitude(), location.getLongitude()); 
    mMap.addMarker(new MarkerOptions().position(myLocation).title("Marker in currentLocation")); 
    mMap.moveCamera(CameraUpdateFactory.newLatLng(myLocation)); 
} 

而這裏的logcat的錯誤:

03-17 17:26:50.857 13753-13753/com.example.casa.gps E/AndroidRuntime: FATAL EXCEPTION: main 
                    Process: com.example.casa.gps, PID: 13753 
                    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 
+0

你在哪裏initializi你的'mMap'? – antonio

+0

在onCreate之前:public GoogleMap mMap –

+0

不,你正在聲明它,不初始化它 – antonio

回答

0

需要初始化你mMap

mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();