我有一个片段,我想在其中显示用户(设备)的当前位置。我使用谷歌地图android api v2。如何得到当前设备的经纬度?
下面你可以看到我使用的代码。不幸的是,应用程序工作错误,不是我所期望的。它只是显示地图,但没有我设置的标记,也没有当前位置。有人能检查一下并修理一下吗?怎么了?谢谢你的帮助!
编辑:
主片段.java
public class MainFragment extends Fragment{
private SupportMapFragment mSupportMapFragment;
private GoogleMap mGoogleMap;
public BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
LatLng temp = new LatLng(extras.getDouble("Latitude"),extras.getDouble("Longitude"));
}
};
@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();
}
//Broadcast/ Filter
IntentFilter filter = new IntentFilter();
filter.addAction(LocationService.BROADCAST_ACTION);
getActivity().registerReceiver(receiver, filter);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
//Start service
getActivity().startService(new Intent(getActivity(),LocationService.class));
}
@Override
public void onResume(){
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "BroadcastReceiver works!");
Bundle extras = intent.getExtras();
final LatLng temp = new LatLng(extras.getDouble("Latitude"),extras.getDouble("Longitude"));
if (mGoogleMap != null) {
mGoogleMap = mSupportMapFragment.getMap();
mGoogleMap.addMarker(new MarkerOptions().position(temp).title("Marker").snippet("Location"));
}
try {
CameraUpdate center = CameraUpdateFactory.newLatLng(temp);
CameraUpdate zoom = CameraUpdateFactory.zoomTo(15f);
mGoogleMap.moveCamera(center);
mGoogleMap.animateCamera(zoom);
}catch (NumberFormatException e) {
//Some code here for exception
}
}
};
}
@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);
}
}
}
fragment_main.xml文件
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/map_container">
<!-- The map fragments will go here -->
</RelativeLayout>
最佳答案
此信息及更多信息可在应用程序可从融合位置提供程序检索的位置对象中获得:https://developer.android.com/training/location/retrieve-current.html。