在 Fragment 的地图中检测当前位置时遇到问题

Posted

技术标签:

【中文标题】在 Fragment 的地图中检测当前位置时遇到问题【英文标题】:Trouble detecting current location in a map in Fragment 【发布时间】:2016-04-13 23:17:42 【问题描述】:

我可以看到地图,但无法放大当前位置。代码在 try-catch 块中中断,并看到 Google Play Services missing !

**这是发生崩溃的地方**

map = mapFragment.getMap();

完整代码如下:

public class MyMapFragment extends Fragment implements
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener,
    LocationListener 

GoogleMap map;
LatLng latlng;
private LocationRequest lr;
private LocationServices lc; //was LocationClient
MapFragment mapFragment;
//ImageView iv;
private static View view;

@Override
public void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);




@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) 

    View view = inflater.inflate(R.layout.fragment_map, container, false);

        SupportMapFragment mMapFragment = SupportMapFragment.newInstance();
        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        transaction.add(R.id.map_container, mMapFragment).commit();

        mapFragment = ((MapFragment) this.getActivity()
                .getFragmentManager().findFragmentById(R.id.map_container));

        map = mapFragment.getMap(); **THIS IS WHERE THE CRASH HAPPENS **
        map.getUiSettings().setAllGesturesEnabled(false);
        map.getUiSettings().setMyLocationButtonEnabled(false);

        if (ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.ACCESS_FINE_LOCATION) // this might need massaged to 'android.permission.USE_FINGERPRINT'
                != PackageManager.PERMISSION_GRANTED) 
            map.setMyLocationEnabled(true);
         else 
            map.setMyLocationEnabled(false);
        

        map.getUiSettings().setZoomControlsEnabled(false);

        MapsInitializer.initialize(getActivity());


    Toast.makeText(getActivity(), "Printing from MyMapFragment", Toast.LENGTH_LONG).show();
    return view;


@Override
public void onAttach(Activity activity) 
    super.onAttach(activity);
    Log.d("Attach", "on attach");


@Override
public void onDetach() 
    super.onDetach();



@Override
public void onConnected(@Nullable Bundle bundle) 



@Override
public void onConnectionSuspended(int i) 



@Override
public void onLocationChanged(Location location) 



@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) 



Android XML 文件:R.layout.fragment_map.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_
android:layout_
android:orientation="vertical">


<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map_container"
    android:layout_
    android:layout_ />


</LinearLayout>

堆栈跟踪

FATAL EXCEPTION: main
                                                                              Process: com.mavdev.gunfreebusinesses, PID: 29988
                                                                                  java.lang.RuntimeException: Unable to start activity  ComponentInfocom.mavdev.gunfreebusinesses/com.mavdev.gunfreebusinesses.activities.MainActivity: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.GoogleMap com.google.android.gms.maps.MapFragment.getMap()' on a null object reference
                                                                              at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2339)
                                                                              at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2413)
                                                                              at android.app.ActivityThread.access$800(ActivityThread.java:155)
                                                                              at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1317)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                              at android.os.Looper.loop(Looper.java:135)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:5343)
                                                                              at java.lang.reflect.Method.invoke(Native Method)
                                                                              at java.lang.reflect.Method.invoke(Method.java:372)
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
                                                                           Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.GoogleMap com.google.android.gms.maps.MapFragment.getMap()' on a null object reference
                                                                              at com.mavdev.gunfreebusinesses.fragments.MyMapFragment.onCreateView(MyMapFragment.java:77)
                                                                              at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
                                                                              at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
                                                                              at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248)
                                                                              at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
                                                                              at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613)
                                                                              at android.support.v4.app.FragmentController.execPendingActions(FragmentController.java:330)
                                                                              at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:547)
                                                                              at com.mavdev.gunfreebusinesses.activities.MainActivity.onStart(MainActivity.java:385)
                                                                              at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1259)
                                                                              at android.app.Activity.performStart(Activity.java:6026)
                                                                              at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2302)
                                                                              at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2413) 
                                                                              at android.app.ActivityThread.access$800(ActivityThread.java:155) 
                                                                              at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1317) 
                                                                              at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                              at android.os.Looper.loop(Looper.java:135) 
                                                                              at android.app.ActivityThread.main(ActivityThread.java:5343) 
                                                                              at java.lang.reflect.Method.invoke(Native Method) 
                                                                              at java.lang.reflect.Method.invoke(Method.java:372) 
                                                                               at     com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905) 
                                                                                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700) 

【问题讨论】:

检查我的编辑答案 您是否尝试过使用getMapAsync?据我所知,getMap 现在已被弃用 【参考方案1】:

Xml 代码

      <fragment android:id="@+id/map_container"
      android:layout_
      android:layout_
      android:name="com.google.android.gms.maps.MapFragment"/>

使用

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

而不是

map = mapFragment.getMap();

在 Activity java 代码中

private MapFragment getMapFragment() 
FragmentManager fm = null;

Log.d(TAG, "sdk: " + Build.VERSION.SDK_INT);
Log.d(TAG, "release: " + Build.VERSION.RELEASE);

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) 
  // using getFragmentManager
    fm = getFragmentManager();
 else 
  //using getChildFragmentManager
    fm = getChildFragmentManager();


return (MapFragment) fm.findFragmentById(R.id.map_container);

【讨论】:

嗨@sasikumar - 我在片段本身中收到此错误。我正在片段的 onCreateView 中尝试这个:i.imgur.com/m2uAaQY.jpg

以上是关于在 Fragment 的地图中检测当前位置时遇到问题的主要内容,如果未能解决你的问题,请参考以下文章

如何在不使用谷歌地图和其他地图的情况下获取用户当前位置?

将 Google 地图缩放到当前位置

将Google地图缩放到当前位置

原神位置检测【OpenCV 特征匹配】

如何在地图上显示当前位置?

检测空气中的位置