0

嗨我需要一些幫助,我已經看過並嘗試許多不同的事情。我試圖讓我在android上的當前位置,但由於位置返回null我的應用程序崩潰。我真的需要這方面的幫助。谷歌地圖v2 API的Android位置返回null

我不知道我是否在這裏清楚,但每次我調用getLastKnownlocation它回來爲空,所以當我嘗試獲得雙lat = location.getLatitude()相同的經度它不會返回任何東西,並有我的應用程序崩潰的地方。

幫助...... 這裏位於北緯一段代碼

mMap.setMyLocationEnabled(true); 
LocationManager locationManager = (LocationManager)getSystemService(LOCATION_SERVICE); 
Criteria criteria = new Criteria(); 

String provider = locationManager.getBestProvider(criteria, true); 

Location location = locationManager.getLastKnownLocation(provider); 

mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); 

double lat = location.getLatitude(); 
double lng = location.getLongitude(); 
LatLng latLng = new LatLng(lat, lng); 

是它停止。

+0

你得到的 字符串提供商提供什麼= locationManager.getBestProvider(標準,真正的);? – CAA 2015-03-02 14:41:24

+1

從來沒有一個位置返回給你,所以你必須始終檢查一個空位置 – tyczj 2015-03-02 14:56:40

+0

@CAA我得到的提供商是這條線上的GPS – 2015-03-02 15:30:52

回答

1

在調用這些函數之前,您是否從該片段中檢索GoogleMap對象?

喜歡的東西:

//get map fragment from the static layout (in this case it has id = "map") 
    MapFragment mapFragment = (MapFragment) getFragmentManager() 
      .findFragmentById(R.id.map); 
//get GoogleMap object, then you can start using it, for example enabling the location 
    map = mapFragment.getMap(); 
    map.setMyLocationEnabled(true); 
+0

是啊@Andrea Montanari它是被調用的,事實上我的地圖可以很好地打開並且沒有任何問題,但是在我編寫代碼以獲取當前位置之前。更清楚,如果我只是這樣做:MapFragment mapFragment =(MapFragment)getFragmentManager() .findFragmentById(R.id.map); map.setMyLocationEnabled(true);它將打開並指向我的位置,但如果我嘗試獲取當前位置,以便相機可以移動到該位置,則會返回null,並使我的應用程序崩潰。 – 2015-03-02 15:46:48

+0

您是否添加了檢索位置所需的權限? – 2015-03-02 19:53:49

+0

是的,我已經添加了所有這些: <用途的許可安卓:名稱=‘android.permission.ACCESS_FINE_LOCATION’/> – 2015-03-02 20:19:08

0

謝謝大家的幫助我很感激,我已經解決了我的問題。 這裏的一段代碼,幫助我得到TI完成:

//I needed to have this line before everything else for me to get my current 
//location from getLastKnownLocation method. 

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

//And the all the codes I had before 
mMap.setMyLocationEnabled(true); 
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
Criteria criteria = new Criteria(); 

String provider = locationManager.getBestProvider(criteria, true); 

Location location = locationManager.getLastKnownLocation(provider); 

mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); 

double lat = location.getLatitude(); 
double lng = location.getLongitude(); 
LatLng latLng = new LatLng(lat, lng); 

mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 
mMap.animateCamera(CameraUpdateFactory.zoomTo(14)); 
mMap.addMarker(new MarkerOptions() 
      .position(new LatLng(lat, lng)) 
      .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)) 
      .title("Here"));