samedi 10 janvier 2015

Unable to get the Android Location API to work


Vote count:

0




My goal is to get the current location of someone and place a marker on that spot on Google Maps. It seems that the location is returning null. When I was debugging, it seemed like the methods for the OnConnection callbacks were not working either. The device is connected and well because I can use the mMap.setMyLocationEnabled which allows for finding location, but does not give data for the location. I am running on a HTC One M8.



private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private LatLng mLastLocationLatLng;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
setUpMapIfNeeded();
}

@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}

private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}


private void setUpMap() {
mMap.setMyLocationEnabled(true);
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng latLng) {
mMap.addMarker(new MarkerOptions().position(latLng).title("Test"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10), 500, null);
}
});

// Zoom in, animating the camera.
//mMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
}

@Override
public void onConnected(Bundle bundle) {
//Gets last location of user - is usually the current
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
mLastLocationLatLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mLastLocationLatLng, 15));
}
else {
LatLng latLng = new LatLng(0,0);
Toast.makeText(this, "Location not Found", Toast.LENGTH_LONG).show();
}


}
@Override
public void onConnectionSuspended(int i) {

}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}


}



asked 1 min ago







Unable to get the Android Location API to work

Aucun commentaire:

Enregistrer un commentaire