谷歌地图当前位置

时间:2014-05-09 04:27:10

标签: java android google-maps

我有一个非常复杂的应用程序,具有各种不同的功能。其中一个功能包括谷歌地图选项卡。应用程序的结构使得每个选项卡都是一个片段。 在这种特殊情况下,我无法声明我的谷歌地图对象获取当前位置数据。

以下是相关代码

public static class GpsClass extends Fragment{
    View rootView;
    private GoogleMap mMap;

    public static final String ARG_SECTION_NUMBER = "section_number";
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        if (rootView != null){
                ((ViewGroup) rootView.getParent()).removeView(rootView);
            }
            try{
                rootView = inflater.inflate(R.layout.gps, container,false);
                mMap = ((SupportMapFragment)getActivity().getSupportFragmentManager().findFragmentById(R.id.mymap)).getMap();
                mMap.setMyLocationEnabled(true);

            } catch(InflateException e){

            }
            return rootView;
        }
    }

在我的代码实现中,当我尝试声明mMap时,我得到一个空指针异常。如果我删除 getAvtivity()调用,eclipse告诉我我不能对非静态方法进行静态引用。如果我删除了mMap行,我的应用程序在一个选项卡中使用谷歌地图(其他选项卡实现其他所有工作)。

2 个答案:

答案 0 :(得分:2)

你能包含你的布局xml吗?

如果地图片段为SupportMapFragmentcom.google.android.gms.maps.SupportMapFragment),请使用:

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

如果地图片段为MapFragmentcom.google.android.gms.maps.MapFragment),请使用:

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

编辑: OP问题的实际答案: 在布局XML中声明它时,请确保使用Map Fragment的正确类名。

答案 1 :(得分:0)

试试这个

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

和你的xml

<fragment
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    class="com.google.android.gms.maps.SupportMapFragment" />