繁体   English   中英

如何使用片段类在mapview上获取当前位置?

[英]How can I get current location on mapview using fragment class?

您好,我是android开发的新手,我想使用fragment类在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) {

}

在清单中,我添加了所有用于Google地图服务的权限

根据文档

如果设备运行的是Android 6.0或更高版本, 并且您的应用程序的目标SDK是23或更高版本:该应用程序必须在清单中列出权限, 并且在运行该应用程序时它必须请求所需的每个危险权限。 用户可以授予或拒绝每个许可,即使用户拒绝许可请求,应用程序也可以继续以有限的功能运行。

这就是为什么尽管您已在清单文件中声明了权限,但仍需要在运行时要求它们的原因。

作为解决方法,您可以将minSdkVersion设置为<23,也可以按照文档中的说明进行设置:

注意:从Android 6.0(API级别23)开始,即使该应用程序定位于较低的API级别,用户也可以随时从任何应用程序撤消权限。 无论您的应用程序面向哪个API级别,都应测试您的应用程序以验证其在缺少所需权限时是否能够正常运行。

另外,根据“ 权限最佳实践”,您应该针对两种权限模型进行测试,以提供更好的用户体验。

尝试这个:

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();
}

清单文件中添加这些使用权限

<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" />

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM