您好我正在使用
显示用户位置地图 googleMap.setMyLocationEnabled(true);
请求许可后。
多数工作,但为什么永远不会调用onLocationChanged方法?可能我应该实现LocationListener,但我真的想知道在处理片段时该怎么做。
public class tab2_fragment extends Fragment {
private static final String TAG = "Tab2Fragment";
MapView mMapView;
private GoogleMap googleMap;
public static final int REQUEST_LOCATION = 1;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab2_fragment, container, false);
mMapView = (MapView) rootView.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume(); // needed to get the map to display immediately
// googleMap.setMapStyle(
// MapStyleOptions.loadRawResourceStyle(
//this, R.raw.mapstyle));
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mMapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
if (ActivityCompat.checkSelfPermission(getContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(getContext(),
android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(),
new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION,
android.Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION);
} else {
Log.e("DB", "PERMISSION GRANTED");
}
googleMap.setMyLocationEnabled(true);
}
public void onLocationChanged(Location location){
LatLng myLocation = new LatLng(location.getLatitude(), location.getLongitude());
googleMap.addMarker(new MarkerOptions()
.position(myLocation)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))
.title("My Location"));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(myLocation));
Log.d("location", "Latitude:" + location.getLatitude() + "\n" + "Longitude:" + location.getLongitude());
}
});
return rootView;
}
}