В настоящее время у меня проблемы с маршрутизацией приложения в определенную точку. Я использую com.github.jd-alexander: библиотека: 1.1.0.
Моя проблема связана со строкой '' '.withListener (this)' '', где я говорю, что требуемый драйвер маршрутизатора обнаружил активность драйвера.
Я считаю, что это также влияет на мою функцию '' 'onRoutingSuccess' '', потому что я не могу вызвать переопределение для нее.
Мой код ниже:
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.*
import androidx.annotation.NonNull
import androidx.core.app.ActivityCompat
import com.directions.route.*
import com.firebase.geofire.GeoFire
import com.firebase.geofire.GeoLocation
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.api.GoogleApiClient
import com.google.android.gms.location.*
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.*
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.*
import java.util.*
class DriverMapActivity : AppCompatActivity(), OnMapReadyCallback {
private var mMap: GoogleMap? = null
internal lateinit var mLastLocation: Location
internal lateinit var mLocationRequest: LocationRequest
private var fusedLocationClient: FusedLocationProviderClient? = null
private lateinit var locationCallback: LocationCallback
private lateinit var locationManager: LocationManager
companion object {
private const val LOCATION_PERMISSION_REQUEST_CODE = 1
private const val REQUEST_CHECK_SETTINGS = 2
private const val PLACE_PICKER_REQUEST = 3
}
private var mLogout: Button? = null
private var mSettings: Button? = null
private var mRideStatus: Button? = null
private var mWorkingSwitch: Switch? = null
private var status = 0
private var customerId = ""
private var destination: String? = null
private var destinationLatLng: LatLng? = null
private var pickupLatLng: LatLng? = null
private var rideDistance: Float = 0.toFloat()
private var isLoggingOut: Boolean? = false
private var mapFragment: SupportMapFragment? = null
private var mCustomerInfo: LinearLayout? = null
private var mCustomerProfileImage: ImageView? = null
private var mCustomerName: TextView? = null
private var mCustomerPhone: TextView? = null
private var mCustomerDestination: TextView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_driver_map)
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
polylines = ArrayList()
mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
Prme()
mapFragment?.getMapAsync(this)
mCustomerInfo = findViewById(R.id.customerInfo) as LinearLayout
mCustomerProfileImage = findViewById(R.id.customerProfileImage) as ImageView
mCustomerName = findViewById(R.id.customerName) as TextView
mCustomerPhone = findViewById<TextView>(R.id.customerPhone)
mCustomerDestination = findViewById<TextView>(R.id.customerDestination)
mWorkingSwitch = findViewById<Switch>(R.id.workingSwitch)
mWorkingSwitch?.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener { buttonView, isChecked ->
if (isChecked) {
connectDriver()
getAssignedCustomer()
Toast.makeText(this, "Turned On", Toast.LENGTH_SHORT).show()
} else {
disconnectDriver()
Toast.makeText(this, "Turned Off", Toast.LENGTH_SHORT).show()
}
})
mSettings = findViewById<Button>(R.id.settings)
mLogout = findViewById<Button>(R.id.logout)
mRideStatus = findViewById<Button>(R.id.rideStatus)
mRideStatus?.setOnClickListener(View.OnClickListener {
when (status) {
1 -> {
status = 2
erasePolylines()
if (destinationLatLng?.latitude != 0.0 && destinationLatLng?.longitude != 0.0) {
getRouteToMarker(destinationLatLng!!)
}
mRideStatus?.text = "drive completed"
}
2 -> {
recordRide()
endRide()
}
}
})
mLogout?.setOnClickListener(View.OnClickListener {
isLoggingOut = true
disconnectDriver()
FirebaseAuth.getInstance().signOut()
val intent = Intent(this@DriverMapActivity, MainActivity::class.java)
startActivity(intent)
finish()
return@OnClickListener
})
mSettings?.setOnClickListener(View.OnClickListener {
val intent = Intent(this@DriverMapActivity, DriverSettingsActivity::class.java)
startActivity(intent)
return@OnClickListener
})
}
private fun getAssignedCustomer() {
val driverId = FirebaseAuth.getInstance().currentUser!!.uid
val assignedCustomerRef = FirebaseDatabase.getInstance().reference.child("Users").child("Drivers").child(driverId)
.child("customerRequest").child("customerRideId")
assignedCustomerRef.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
if (dataSnapshot.exists()) {
status = 1
customerId = dataSnapshot.value!!.toString()
getAssignedCustomerPickupLocation()
getAssignedCustomerDestination()
getAssignedCustomerInfo()
} else {
endRide()
}
}
override fun onCancelled(databaseError: DatabaseError) {}
})
}
internal var pickupMarker: Marker? = null
private var assignedCustomerPickupLocationRef: DatabaseReference? = null
private var assignedCustomerPickupLocationRefListener: ValueEventListener? = null
private fun getAssignedCustomerPickupLocation() {
assignedCustomerPickupLocationRef =
FirebaseDatabase.getInstance().reference.child("customerRequest").child(customerId)
.child("l")
assignedCustomerPickupLocationRefListener = assignedCustomerPickupLocationRef!!.addValueEventListener(object :
ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
if (dataSnapshot.exists() && customerId != "") {
val map = dataSnapshot.value as List<Any>
var locationLat = 0.0
var locationLng = 0.0
locationLat = java.lang.Double.parseDouble(map[0].toString())
locationLng = java.lang.Double.parseDouble(map[1].toString())
pickupLatLng = LatLng(locationLat, locationLng)
pickupMarker = mMap?.addMarker(
MarkerOptions().position(pickupLatLng!!).title("pickup location")//.icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_pickup)
)
getRouteToMarker(pickupLatLng!!)
}
}
override fun onCancelled(databaseError: DatabaseError) {}
})
}
private fun getAssignedCustomerDestination() {
val driverId = FirebaseAuth.getInstance().currentUser!!.uid
val assignedCustomerRef =
FirebaseDatabase.getInstance().reference.child("Users").child("Drivers").child(driverId)
.child("customerRequest")
assignedCustomerRef.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
if (dataSnapshot.exists()) {
val map = dataSnapshot.value as Map<String, Any>?
if (map!!["destination"] != null) {
destination = map["destination"].toString()
mCustomerDestination?.text = "Destination: $destination"
} else {
mCustomerDestination?.text = "Destination: --"
}
var destinationLat: Double? = 0.0
var destinationLng: Double? = 0.0
if (map["destinationLat"] != null) {
destinationLat = java.lang.Double.valueOf(map["destinationLat"].toString())
}
if (map["destinationLng"] != null) {
destinationLng = java.lang.Double.valueOf(map["destinationLng"].toString())
destinationLatLng = LatLng(destinationLat!!, destinationLng!!)
}
}
}
override fun onCancelled(databaseError: DatabaseError) {}
})
}
private fun getAssignedCustomerInfo() {
mCustomerInfo?.visibility = View.VISIBLE
val mCustomerDatabase =
FirebaseDatabase.getInstance().reference.child("Users").child("Customers")
.child(customerId)
mCustomerDatabase.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
if (dataSnapshot.exists() && dataSnapshot.childrenCount > 0) {
val map = dataSnapshot.value as Map<String, Any>?
if (map!!["name"] != null) {
mCustomerName?.text = map["name"].toString()
}
if (map["phone"] != null) {
mCustomerPhone?.text = map["phone"].toString()
}
if (map["profileImageUrl"] != null) {
Glide.with(application).load(map["profileImageUrl"].toString())
.into(mCustomerProfileImage)
}
}
}
override fun onCancelled(databaseError: DatabaseError) {}
})
}
private fun endRide() {
mRideStatus?.text = "picked customer"
erasePolylines()
val userId = FirebaseAuth.getInstance().currentUser!!.uid
val driverRef =
FirebaseDatabase.getInstance().reference.child("Users").child("Drivers").child(userId)
.child("customerRequest")
driverRef.removeValue()
val ref = FirebaseDatabase.getInstance().getReference("customerRequest")
val geoFire = GeoFire(ref)
geoFire.removeLocation(customerId)
customerId = ""
rideDistance = 0f
if (pickupMarker != null) {
pickupMarker!!.remove()
}
if (assignedCustomerPickupLocationRefListener != null) {
assignedCustomerPickupLocationRef!!.removeEventListener(
assignedCustomerPickupLocationRefListener!!
)
}
mCustomerInfo?.visibility = View.GONE
mCustomerName?.text = ""
mCustomerPhone?.text = ""
mCustomerDestination?.text = "Destination: --"
mCustomerProfileImage?.setImageResource(R.mipmap.ic_default_user)
}
private fun recordRide() {
val userId = FirebaseAuth.getInstance().currentUser!!.uid
val driverRef =
FirebaseDatabase.getInstance().reference.child("Users").child("Drivers").child(userId)
.child("history")
val customerRef = FirebaseDatabase.getInstance().reference.child("Users").child("Customers")
.child(customerId).child("history")
val historyRef = FirebaseDatabase.getInstance().reference.child("history")
val requestId = historyRef.push().key
driverRef.child(requestId!!).setValue(true)
customerRef.child(requestId).setValue(true)
val map = HashMap<String,Any?>()
map["driver"] = userId
map["customer"] = customerId
map["rating"] = 0
map["timestamp"] = getCurrentTimestamp()
map["destination"] = destination
map["location/from/lat"] = pickupLatLng?.latitude
map["location/from/lng"] = pickupLatLng?.longitude
map["location/to/lat"] = destinationLatLng?.latitude
map["location/to/lng"] = destinationLatLng?.longitude
map["distance"] = rideDistance
historyRef.child(requestId).updateChildren(map)
}
private fun getCurrentTimestamp(): Long? {
return System.currentTimeMillis() / 1000
}
override fun onMapReady(googleMap: GoogleMap) {
mMap = googleMap
mLocationRequest = LocationRequest()
mLocationRequest.interval = 1000
mLocationRequest.fastestInterval = 1000
mLocationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
mapLocationService()
setUpMap()
mMap!!.isMyLocationEnabled = true
}
private fun setUpMap() {
Prme()
mMap!!.isMyLocationEnabled = true
mMap!!.mapType = GoogleMap.MAP_TYPE_NORMAL
fusedLocationClient?.lastLocation?.addOnSuccessListener(this) { location ->
// Got last known location. In some rare situations this can be null.
if (location != null) {
mLastLocation = location
val currentLatLng = LatLng(location.latitude, location.longitude)
mMap?.animateCamera(CameraUpdateFactory.newLatLngZoom(currentLatLng, 12f))
}
}
}
private fun mapLocationService(){
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
locationCallback = object : LocationCallback() {
override fun onLocationResult(p0: LocationResult) {
super.onLocationResult(p0)
mLastLocation = p0.lastLocation
}
}
}
private fun connectDriver() {
Prme()
fusedLocationClient?.lastLocation?.addOnSuccessListener(this) { location ->
if (customerId != "") {
rideDistance += mLastLocation.distanceTo(location) / 1000
}
mLastLocation = location
val latLng = LatLng(location.latitude, location.longitude)
mMap?.moveCamera(CameraUpdateFactory.newLatLng(latLng))
mMap?.animateCamera(CameraUpdateFactory.zoomTo(11f))
val userId = FirebaseAuth.getInstance().currentUser!!.uid
val refAvailable = FirebaseDatabase.getInstance().getReference("driversAvailable")
val refWorking = FirebaseDatabase.getInstance().getReference("driversWorking")
val geoFireAvailable = GeoFire(refAvailable)
val geoFireWorking = GeoFire(refWorking)
when (customerId) {
"" -> {
geoFireWorking.removeLocation(userId)
geoFireAvailable.setLocation(userId, GeoLocation(location.latitude, location.longitude), object : GeoFire.CompletionListener {
override fun onComplete(key: String?, error: DatabaseError?) {
Toast.makeText(this@DriverMapActivity, "you are available for work ", Toast.LENGTH_LONG).show();
}
})
}
else -> {
geoFireAvailable.removeLocation(userId)
geoFireAvailable.setLocation(userId, GeoLocation(location.latitude, location.longitude), object : GeoFire.CompletionListener {
override fun onComplete(key: String?, error: DatabaseError?) {
}
})
}
}
}
}
private fun disconnectDriver() {
Prme()
fusedLocationClient?.lastLocation?.addOnSuccessListener(this) { location ->
val userId = FirebaseAuth.getInstance().currentUser!!.uid
val ref = FirebaseDatabase.getInstance().getReference("driversAvailable")
val geoFire = GeoFire(ref)
geoFire.removeLocation(userId)
Toast.makeText(this@DriverMapActivity, "you have gone offline", Toast.LENGTH_SHORT).show();
}
}
internal val LOCATION_REQUEST_CODE = 1
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when (requestCode) {
LOCATION_REQUEST_CODE -> {
if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mapFragment?.getMapAsync(OnMapReadyCallback {})
} else {
Toast.makeText(applicationContext, "Please provide the permission", Toast.LENGTH_LONG).show()
}
}
}
}
private var polylines: MutableList<Polyline>? = null
private val COLORS = intArrayOf(R.color.primary_dark_material_light)
private fun getRouteToMarker(pickupLatLng: LatLng) {
val googleKey = ""
val routing = Routing.Builder().key(googleKey)
.travelMode(AbstractRouting.TravelMode.DRIVING)
.withListener(this)
.alternativeRoutes(false)
.waypoints(LatLng(mLastLocation.latitude, mLastLocation.longitude), pickupLatLng)
.build()
routing.execute()
}
fun onRoutingFailure(e: RouteException?) {
if (e != null) {
Toast.makeText(this, "Error: " + e.message, Toast.LENGTH_LONG).show()
} else {
Toast.makeText(this, "Something went wrong, Try again", Toast.LENGTH_SHORT).show()
}
}
fun onRoutingStart() {}
fun onRoutingSuccess(route: ArrayList<Route>, shortestRouteIndex: Int) {
if (polylines!!.size > 0) {
for (poly in polylines!!) {
poly.remove()
}
}
polylines = ArrayList()
//add route(s) to the map.
for (i in route.indices) {
//In case of more than 5 alternative routes
val colorIndex = i % COLORS.size
val polyOptions = PolylineOptions()
polyOptions.color(resources.getColor(COLORS[colorIndex]))
polyOptions.width((10 + i * 3).toFloat())
polyOptions.addAll(route[i].points)
val polyline = mMap?.addPolyline(polyOptions)
polyline?.let { polylines!!.add(it) }
Toast.makeText(
applicationContext,
"Route " + (i + 1) + ": distance - " + route[i].distanceValue + ": duration - " + route[i].durationValue,
Toast.LENGTH_SHORT
).show()
}
}
private fun erasePolylines() {
for (line in polylines!!) {
line.remove()
}
polylines!!.clear()
}
private fun Prme() {
if (ActivityCompat.checkSelfPermission(
this,
android.Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION),
DriverMapActivity.LOCATION_PERMISSION_REQUEST_CODE
)
return
}
}
// Creating Table
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.drawer_menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.itemId
if (id == R.id.SignOutClicked) {
FirebaseAuth.getInstance().signOut()
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
Toast.makeText(this, "Signing Out", Toast.LENGTH_LONG).show()
return true
}
if (id == R.id.settings) {
val intent = Intent(this, CustomerSettingsActivity::class.java)
startActivity(intent)
Toast.makeText(this, "Settings", Toast.LENGTH_LONG).show()
return true
}
if (id == R.id.history) {
Toast.makeText(this, "Item Three Clicked", Toast.LENGTH_LONG).show()
return true
}
return super.onOptionsItemSelected(item)
}
} '' '