如何在Google Maps API V2中获取当前位置

Xar*_*lon 11 null android google-maps-android-api-2

我正在创建一个应用程序,用户需要使用getMyLocation()查看他/她的地理位置,但这将返回null.有没有任何解决方案,因为我确实读到getMyLocation()方法总是返回null.我是谷歌地图新手,所以任何帮助将不胜感激!

码:

GoogleMap map = ((SupportMapFragment)  getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
map.setMyLocationEnabled(true);
Location myLocation = map.getMyLocation();

if( myLocation != null ){
    helper.showToast( "Latitude: " + myLocation.getLatitude() + "\nLongitude: " + myLocation.getLongitude() );
}
Run Code Online (Sandbox Code Playgroud)

小智 15

private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            mMap.setMyLocationEnabled(true);
            // Check if we were successful in obtaining the map.
            if (mMap != null) {


             mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {

           @Override
           public void onMyLocationChange(Location arg0) {
            // TODO Auto-generated method stub

             mMap.addMarker(new MarkerOptions().position(new LatLng(arg0.getLatitude(), arg0.getLongitude())).title("It's Me!"));
           }
          });

            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

在创建函数中调用此函数


Rah*_*tel 0

请检查示例代码Google Maps Android API v2,使用它您将解决您的问题。

示例代码