我使用Fragment实现了LocationListener,我试图获取我当前的位置,但我无法成功。我错过了什么吗?
public class TrafficInformation extends Fragment implements LocationListener{
private MapView mapView;
private GoogleMap googleMap;
private double myLatitude,myLongitude;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.traffic_information_fragment, container, false);
mapView = (MapView) view.findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
mapView.onResume();
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
//part of android 6.0 permission
int flag = ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION);
if (flag != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
} else {
googleMap.setMyLocationEnabled(true);
}
// For dropping a marker at a point on the Map
//i set my current location over here-------------------
LatLng sydney = new LatLng(myLatitude, myLongitude);
googleMap.addMarker(new MarkerOptions().position(sydney).title("Marker Title").snippet("Marker Description"));
//For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(16).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
});
return view;
}
我试图从这个功能中获取它:
@Override
public void onLocationChanged(Location location) {
myLatitude=location.getLatitude();
myLongitude=location.getLongitude();
}
我无法获得myLatitude和myLongitude位置,为什么? 任何帮助都会感激不尽。
答案 0 :(得分:1)
你没有打电话
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this)
你只是在打电话
googleMap.setMyLocationEnabled(true);
这不要求更新位置...只需在地图上的位置设置一个图钉。
点击此处查看如何申请当前位置:
https://developer.android.com/training/location/receive-location-updates.html