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"));