0
我正在使用適用於Android v2的Google地圖。我想顯示當前的用戶位置並放大它。當然有很多關於這方面的材料,但大多數都使用了Activity。在我的情況下,我使用Fragment。當前用戶位置Google地圖API v2中的片段(NOT ACTIVITY)
這裏是片段它只是顯示地圖中的代碼:onyone 檢查並修復它?
public class MainFragment extends Fragment{
private SupportMapFragment mSupportMapFragment;
private GoogleMap mGoogleMap;
private LocationManager mLocationManager;
private LocationListener mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
getCurrentLocation();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
FragmentManager mFragmentManager = getChildFragmentManager();
mSupportMapFragment = (SupportMapFragment) mFragmentManager.findFragmentById(R.id.map_container);
if (mSupportMapFragment == null) {
mSupportMapFragment = SupportMapFragment.newInstance();
mFragmentManager.beginTransaction().replace(R.id.map_container, mSupportMapFragment).commit();
}
}
void getCurrentLocation(){
mLocationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,mLocationListener);
Location myLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
//Location myLocation = mGoogleMap.getMyLocation();
if(myLocation!=null)
{
double dLatitude = myLocation.getLatitude();
double dLongitude = myLocation.getLongitude();
Log.i("APPLICATION"," : "+dLatitude);
Log.i("APPLICATION"," : "+dLongitude);
mGoogleMap.addMarker(new MarkerOptions().position(new LatLng(dLatitude, dLongitude)).title("My Location").snippet("Location"));
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(dLatitude, dLongitude), 8));
}
else
{
Toast.makeText(getActivity(), "Unable to fetch the current location", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onDetach() {
super.onDetach();
try {
Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
childFragmentManager.setAccessible(true);
childFragmentManager.set(this, null);
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
感謝您的幫助!
hello!當然。我正在嘗試獲取設備的當前經緯度。你知道如何服用嗎? – 2015-02-09 18:56:54
你好@larryp!你好嗎?我可以在哪裏調用這個函數?在onLocationChanged方法中調用它會更好嗎? – 2015-02-12 14:42:49
我更新了我的帖子,你可以檢查它嗎? – 2015-02-12 15:00:38