I have the following problem. I receive in my LocationChangeListeningCallback latitude and longitude but getting the speed is not possible. It is always 0.
Here is my code (I hope I have not omitted anything).
AndroidManidest.xml
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
build.gradle
//MapBox
implementation 'com.mapbox.mapboxsdk:mapbox-android-sdk:8.6.2'
implementation('com.google.android.gms:play-services-location:18.0.0')
MainActivity.kt
override fun onMapReady(mapboxMap: MapboxMap) {
map = mapboxMap
callback = LocationChangeListeningCallback()
mapboxMap.setStyle(Style.MAPBOX_STREETS) {
enableLocationComponent(it)
}
}
private inner class LocationChangeListeningCallback : LocationEngineCallback { override fun onSuccess(result: LocationEngineResult?) { result?.lastLocation ?: return if (result.lastLocation != null){ val lat = result.lastLocation?.latitude!! val lng = result.lastLocation?.longitude!! val latLng = LatLng(lat, lng)
if (result.lastLocation != null) {
map.locationComponent.forceLocationUpdate(result.lastLocation)
val position = CameraPosition.Builder()
.target(latLng)
.zoom(13.0)
.tilt(10.0)
.build()
map.animateCamera(CameraUpdateFactory.newCameraPosition(position))
point = Point.fromLngLat(lng, lat)
pointList.add(point)
if(pointList.size>1) {
var location = Location(LocationManager.GPS_PROVIDER)
val results = FloatArray(5)
val lastlat = pointList[pointList.lastIndex - 1]
var xLng = lastlat.coordinates()[0]
var yLat = lastlat.coordinates()[1]
Location.distanceBetween(yLat, xLng, lat, lng, results)
//--> Here speed is always 0.0
if(location.hasSpeed())
speed = location.speed/18*5
else
speed = 0F
accDistance += results[0]
textViewDistance.text = "Distance in meters covered: " + accDistance + "\n" + "Current Velocity: " + speed
} else {
textViewDistance.text = "Distance in meters covered: 0.0" + "\n" + "Current Velocity: 0"
}
map_view.getMapAsync(OnMapReadyCallback { mapboxMap ->
mapboxMap.setStyle(Style.MAPBOX_STREETS) { style ->
// Create the LineString from the list of coordinates and then make a GeoJSON
// FeatureCollection so we can add the line to our map as a layer
style.addSource(
GeoJsonSource(
"line-source",
FeatureCollection.fromFeatures(
arrayOf(
Feature.fromGeometry(
LineString.fromLngLats(pointList)
)
)
)
)
)
// The layer properties for our line
style.addLayer(
LineLayer("linelayer", "line-source").withProperties(
PropertyFactory.lineWidth(3f),
PropertyFactory.lineColor(Color.parseColor("#FF0000"))
)
)
}
})
}
}
}
override fun onFailure(exception: Exception) {}
}
I hope somebody can help me. I have not found anything on the Internet to solve my problem.