我尝试了很多不同的解决方案,我也在Google上进行了搜索,但仍未获得所需的解决方案。问题尚未解决。我有ViewPager和一些片段。在第一篇片段中,我想使用Google Map API v2来显示设备的当前位置。如果我使用纬度/经度的当前值并进行缩放,它可以正常工作。什么是了解片段中当前位置( NOT FragmentActivity或Activity )当前纬度和经度的最佳方式?我只是想知道Fragment有可能吗?如果有人有同样的问题并解决了,请告诉我!
感谢您的帮助!
下面是我用来设置地图的代码:
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);
}
}
}
答案 0 :(得分:0)
。试试这个..
LocationManager lm;
Location location;
Geocoder geo;
//convert lat, long to address.
List<Address> addresses;
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//get the last known latitude longitude from network
location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//create an instance of geocoder
geo = new Geocoder(this.getApplicationContext(), Locale.getDefault());
try
{
addresses = geo.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if(addresses.get(0).getPostalCode() != null)
{
//You can get Lat, Long or Zip code
}
}
catch (Exception e)
{
}