如何使用片段 class 在 mapview 上获取当前位置?
How can I get current location on mapview using fragment class?
您好,我是 android 开发新手,我想使用片段 class 在 mapview 中获取当前位置。当我添加 setMyLocationEnabled 方法时,它正在请求权限,并且我已经在清单中添加了所有权限。请帮助我。
Gmaps.java(片段)
public class Gmaps extends Fragment implements OnMapReadyCallback {
private GoogleMap googleMap;
private MapView mapView;
private boolean mapsSupported = true;
private GoogleApiClient mGoogleApiClient;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MapsInitializer.initialize(getActivity());
if (mapView != null) {
mapView.onCreate(savedInstanceState);
}
initializeMap();
}
private void initializeMap() {
if (googleMap == null && mapsSupported) {
mapView = (MapView) getActivity().findViewById(R.id.map);
googleMap = mapView.getMap();
double latitude = 0.00;
double longitude = 0.00;
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Marker");
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder().target(
new LatLng(0, 0)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
googleMap.getUiSettings().setZoomControlsEnabled(true); // true to enable
googleMap.getUiSettings().setZoomGesturesEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final FrameLayout p = (FrameLayout) inflater.inflate(R.layout.fragment_gmaps, container, false);
mapView = (MapView) p.findViewById(R.id.map);
return p;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
public void onResume() {
super.onResume();
mapView.onResume();
initializeMap();
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public void onMapReady(GoogleMap googleMap) {
}
在 Manifest 中,我添加了用于 google 地图服务的所有这些权限
试试这个:
public void showMap() {
mapFragment = (SupportMapFragment)getChildFragmentManager().findFragmentById(R.id.map);
if (map == null) {
map = mapFragment.getMap();
}
// Enable Zoom
map.getUiSettings().setZoomGesturesEnabled(true);
//set Map TYPE
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//enable Current location Button
map.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager)getActivity().getSystemService(getActivity().LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(bestProvider, 2000, 0, this);
}
@Override
public void onLocationChanged(Location location) {
latitude= location.getLatitude();
longitude=location.getLongitude();
LatLng loc = new LatLng(latitude, longitude);
if (marker!=null){
marker.remove();
}
marker= map.addMarker(new MarkerOptions().position(loc).title("Sparx IT Solutions"));
map.moveCamera(CameraUpdateFactory.newLatLng(loc));
map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
}
@Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
Toast.makeText(getActivity().getBaseContext(), "Gps is turned off!!",
Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderEnabled(String provider) {
Toast.makeText(getActivity().getBaseContext(), "Gps is turned on!! ",
Toast.LENGTH_SHORT).show();
}
在Manifest 文件
中添加这些使用权限
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
If the device is running Android 6.0 or higher, and your app's target SDK is 23 or higher: The app has to list the permissions in the manifest, and it must request each dangerous permission it needs while the app is running. The user can grant or deny each permission, and the app can continue to run with limited capabilities even if the user denies a permission request.
这就是为什么即使您已经在清单文件中声明了权限,您仍然需要在运行时请求它们的原因。
作为解决方法,您可以设置 minSdkVersion
< 23,但也如文档所述:
Note: Beginning with Android 6.0 (API level 23), users can revoke permissions from any app at any time, even if the app targets a lower API level. You should test your app to verify that it behaves properly when it's missing a needed permission, regardless of what API level your app targets.
此外,根据 Permissions Best Practices 您应该针对两种权限模型进行测试以提供更好的用户体验。
您好,我是 android 开发新手,我想使用片段 class 在 mapview 中获取当前位置。当我添加 setMyLocationEnabled 方法时,它正在请求权限,并且我已经在清单中添加了所有权限。请帮助我。
Gmaps.java(片段)
public class Gmaps extends Fragment implements OnMapReadyCallback {
private GoogleMap googleMap;
private MapView mapView;
private boolean mapsSupported = true;
private GoogleApiClient mGoogleApiClient;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MapsInitializer.initialize(getActivity());
if (mapView != null) {
mapView.onCreate(savedInstanceState);
}
initializeMap();
}
private void initializeMap() {
if (googleMap == null && mapsSupported) {
mapView = (MapView) getActivity().findViewById(R.id.map);
googleMap = mapView.getMap();
double latitude = 0.00;
double longitude = 0.00;
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Marker");
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder().target(
new LatLng(0, 0)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
googleMap.getUiSettings().setZoomControlsEnabled(true); // true to enable
googleMap.getUiSettings().setZoomGesturesEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final FrameLayout p = (FrameLayout) inflater.inflate(R.layout.fragment_gmaps, container, false);
mapView = (MapView) p.findViewById(R.id.map);
return p;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
public void onResume() {
super.onResume();
mapView.onResume();
initializeMap();
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public void onMapReady(GoogleMap googleMap) {
}
在 Manifest 中,我添加了用于 google 地图服务的所有这些权限
试试这个:
public void showMap() {
mapFragment = (SupportMapFragment)getChildFragmentManager().findFragmentById(R.id.map);
if (map == null) {
map = mapFragment.getMap();
}
// Enable Zoom
map.getUiSettings().setZoomGesturesEnabled(true);
//set Map TYPE
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//enable Current location Button
map.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager)getActivity().getSystemService(getActivity().LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(bestProvider, 2000, 0, this);
}
@Override
public void onLocationChanged(Location location) {
latitude= location.getLatitude();
longitude=location.getLongitude();
LatLng loc = new LatLng(latitude, longitude);
if (marker!=null){
marker.remove();
}
marker= map.addMarker(new MarkerOptions().position(loc).title("Sparx IT Solutions"));
map.moveCamera(CameraUpdateFactory.newLatLng(loc));
map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
}
@Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
Toast.makeText(getActivity().getBaseContext(), "Gps is turned off!!",
Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderEnabled(String provider) {
Toast.makeText(getActivity().getBaseContext(), "Gps is turned on!! ",
Toast.LENGTH_SHORT).show();
}
在Manifest 文件
中添加这些使用权限<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
If the device is running Android 6.0 or higher, and your app's target SDK is 23 or higher: The app has to list the permissions in the manifest, and it must request each dangerous permission it needs while the app is running. The user can grant or deny each permission, and the app can continue to run with limited capabilities even if the user denies a permission request.
这就是为什么即使您已经在清单文件中声明了权限,您仍然需要在运行时请求它们的原因。
作为解决方法,您可以设置 minSdkVersion
< 23,但也如文档所述:
Note: Beginning with Android 6.0 (API level 23), users can revoke permissions from any app at any time, even if the app targets a lower API level. You should test your app to verify that it behaves properly when it's missing a needed permission, regardless of what API level your app targets.
此外,根据 Permissions Best Practices 您应该针对两种权限模型进行测试以提供更好的用户体验。