我正在尝试实现一个导航抽屉,它在片段中有一个地图.这是我的代码.
这里是 fragment_map.xml
然后我在我的网站上调用了FragmentMap ExtractMenu.java
public void onNavigationDrawerItemSelected(int position) { Fragment fragment = null; switch (position){ case 0: fragment = new FragmentMap(); break; } if (fragment != null){ FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.container, fragment).commit(); } }
然后在FragmentMap.java
下面的代码中添加了缩放,ap到当前位置.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mMap.setMyLocationEnabled(true); // Identify the current location of the device mMap.setOnMyLocationChangeListener(this); // change the place when the device is moving Location currentLocation = getMyLocation(); // Calling the getMyLocation method // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_fragment_map, container, false); } // Implement getMyLocation public Location getMyLocation() { LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); // Get location from GPS if it's available Location myLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); // Location wasn't found, check the next most accurate place for the current location if (myLocation == null) { Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_COARSE); // Finds a provider that matches the criteria String provider = lm.getBestProvider(criteria, true); // Use the provider to get the last known location myLocation = lm.getLastKnownLocation(provider); } return myLocation; }
在这里我无法解决getSystemService
任何人都知道为什么?有没有更好的方法来缩放片段中的地图?
Fragment中的getActivity()返回Fragment当前与之关联的Activity.
你正在使用Fragment,所以你需要添加getActivity()
.我希望它能帮到你.
最后,
LocationManager lm = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);