Skip to content

Commit

Permalink
Android - Fixed Location.getLocation() returning null due to getLastL…
Browse files Browse the repository at this point in the history
…ocation() not having a last location
  • Loading branch information
myles_wilter_heritage committed Jan 24, 2019
1 parent b6e7736 commit 6666cf8
Showing 1 changed file with 40 additions and 22 deletions.
62 changes: 40 additions & 22 deletions android/src/main/java/com/lyokone/location/LocationPlugin.java
Original file line number Diff line number Diff line change
Expand Up @@ -224,34 +224,52 @@ private void getLastLocation(final Result result) {
@Override
public void onSuccess(Location location) {
if (location != null) {
HashMap<String, Double> loc = new HashMap<String, Double>();
loc.put("latitude", location.getLatitude());
loc.put("longitude", location.getLongitude());
loc.put("accuracy", (double) location.getAccuracy());
loc.put("altitude", location.getAltitude());
loc.put("speed", (double) location.getSpeed());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
loc.put("speed_accuracy", (double) location.getSpeedAccuracyMetersPerSecond());
}

if (result != null) {
result.success(loc);
return;
}
if (events != null) {
events.success(loc);
}
handleGetLastLocationResponse(location, result);
} else {
if (result != null) {
result.error("ERROR", "Failed to get location.", null);
return;
}
// Do not send error on events otherwise it will produce an error
// Last location is null requestLocationUpdates required
mFusedLocationClient.requestLocationUpdates(mLocationRequest, new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);

Location location = locationResult.getLastLocation();
if (location != null) {
handleGetLastLocationResponse(location, result);
} else {
if (result != null) {
result.error("ERROR", "Failed to get location.", null);
return;
}
// Do not send error on events otherwise it will produce an error
}
mFusedLocationClient.removeLocationUpdates(this);
}
}, Looper.myLooper());
}
}
});
}

private void handleGetLastLocationResponse(Location location, Result result) {
HashMap<String, Double> loc = new HashMap<String, Double>();
loc.put("latitude", location.getLatitude());
loc.put("longitude", location.getLongitude());
loc.put("accuracy", (double) location.getAccuracy());
loc.put("altitude", location.getAltitude());
loc.put("speed", (double) location.getSpeed());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
loc.put("speed_accuracy", (double) location.getSpeedAccuracyMetersPerSecond());
}

if (result != null) {
result.success(loc);
return;
}
if (events != null) {
events.success(loc);
}
}

@Override
public void onMethodCall(MethodCall call, final Result result) {
if (call.method.equals("getLocation")) {
Expand Down

0 comments on commit 6666cf8

Please sign in to comment.