I tried so many different solutions and I also searched on Google but still not getting the required solution. The problem is not yet fixed. I have ViewPager with some Fragments. In first Fragment I wanna use Google Map API v2 to show current location of device. It works fine if I use current values of latitude/longitude and zoom it. Whats the best way to know current latitude and longitude of current location in Fragment (NOT FragmentActivity or Activity)? I just want to know is it possible in Fragment? Let me know please if someone had same problem and solved it!
Thanks for any help!
Here below code that I used to set map:
fragment.xml
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/map_container">
<!-- The map fragments will go here -->
</RelativeLayout>
MainFragment.java
public class MainFragment extends Fragment{
private SupportMapFragment mSupportMapFragment;
private GoogleMap mGoogleMap;
@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();
}
}
@Override
public void onResume(){
if(mGoogleMap==null){
mGoogleMap = mSupportMapFragment.getMap();
//Set the marker
mGoogleMap.addMarker(new MarkerOptions()
.position(new LatLng(???))
.title("Location")
.snippet("Your current location"));
// Move the camera and zoom it to location
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(???), 15));
}
}
@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);
}
}
}