Как удалить путевую точку в приложении Google Maps после того, как пользователь проехал эту точку на маршрутеAndroid

Форум для тех, кто программирует под Android
Ответить Пред. темаСлед. тема
Anonymous
 Как удалить путевую точку в приложении Google Maps после того, как пользователь проехал эту точку на маршруте

Сообщение Anonymous »

Я работаю над мобильным приложением, позволяющим использовать карты Google для прокладки маршрутов и добавления путевых точек к маршруту и ​​сопровождающих их маркеров на карте. Я намерен сделать так, чтобы приложение удаляло путевую точку из маршрута и, возможно, ее маркер, чтобы предотвратить перенаправление карты и показывать направления возвращения к уже пройденному маркеру. Я проверил различные способы сделать это с помощью Chatgpt и пытаюсь найти онлайн-ресурсы, но не нашел хороших ресурсов.
Я пробовал использовать различные решения из Chatgpt, но это не так. не работает. Я также пытался придумать способы удаления путевых точек из маршрута, но это не дало того, что я хотел.
var liveLocation = LocationService.locationData.value
val liveLocationMarkerState = rememberMarkerState()

LaunchedEffect(liveLocation) {
liveLocation?.let { location ->
liveLocationMarkerState.position = location // Update the position of the marker
}
}

var userLocation by remember { mutableStateOf(null) }
val location1 = LatLng(-1.5257693, 36.886121)
val cameraPositionState = rememberCameraPositionState {
position = CameraPosition.fromLatLngZoom(location1, 12f)
}

val markerStatesRoute = remember { mutableStateListOf(null) }

// Request location permissions and start location updates if permissions are granted
val requestPermissionLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.RequestPermission()
) { isGranted: Boolean ->
if (isGranted) {
startLocationService(context)
} else {
liveLocation = location1
}
}

// Define a LaunchedEffect to request permissions and start location updates
LaunchedEffect(requestPermissionLauncher) {
if (ActivityCompat.checkSelfPermission(
context,
Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED
) {
// Permission is already granted
startLocationService(context)
} else {
// Request permission if not granted
requestPermissionLauncher.launch(Manifest.permission.ACCESS_FINE_LOCATION)
}
}

var place by remember { mutableStateOf(null) }

val markerState = rememberMarkerState(
position = LatLng(-1.7198691, 34.9230177)
) // Example coordinates

var routePoints by remember { mutableStateOf(emptyList()) }

val apiKey = getApiKeyFromManifest(LocalContext.current)
var keyy: String = ""
if (apiKey != null) {
keyy = apiKey
} else {
// Handle error: API key not found
}

val waypoint1MarkerState = rememberMarkerState()

var distanceState: Int? = null
var durationState: Int? = null

LaunchedEffect(place) {
place?.let {
cameraPositionState.animate(CameraUpdateFactory.newLatLngZoom(it, 15f))
}
}

// Not able to implement
fun hasPassedWaypoint(
userLocation: LatLng,
waypoint: LatLng,
threshold: Double = 0.01
): Boolean {
// Calculate the distance between the user's location and the waypoint
val distance = sqrt(
(userLocation.latitude - waypoint.latitude) * (userLocation.latitude - waypoint.latitude) +
(userLocation.longitude - waypoint.longitude) * (userLocation.longitude - waypoint.longitude)
)
return distance > threshold
}

// Filtering out passed waypoints
// Does not work!!
val updatedWaypoints = markerStatesRoute
.filterNotNull()
.filter { waypoint ->
liveLocation?.let { location ->
!hasPassedWaypoint(location, waypoint)
} ?: true // If liveLocation is null, don't filter out the waypoint
}

val waypointsString = markerStatesRoute
.filterNotNull()
.joinToString(separator = "|") { marker ->
"${marker.latitude},${marker.longitude}"
}

Log.d("Waypoints", "Waypoints string: $waypointsString")

LaunchedEffect(place, liveLocation, waypointsString) {
place?.let {
try {
val directionsResponse =
RetrofitInstance.directionsService.getDirections(
origin = "${liveLocation?.latitude},${liveLocation?.longitude}",
destination = "${it.latitude},${it.longitude}",
waypoints = waypointsString, // Use pipes to separate waypoints
apiKey = "_YOUR_API_KEY_"
)

Log.d("DirectionsService", "DirectionsResponse: $directionsResponse")

val encodedPolyline =
directionsResponse.routes?.firstOrNull()?.overview_polyline?.points
if (!encodedPolyline.isNullOrEmpty()) {
routePoints = decodePolyline(encodedPolyline)
}

val route = directionsResponse.routes?.firstOrNull()

// Update UI or state
// Example: update distance and duration state
distanceState = distance
durationState = duration
} catch (e: Exception) {
// Handle exceptions (e.g., API errors)
e.printStackTrace()
}
}
}

// Initialize the marker state
val selectedMarkerState = rememberMarkerState()

// Update the camera position and marker position when place changes
LaunchedEffect(place) {
place?.let {
// Move the camera to the new location
cameraPositionState.animate(
CameraUpdateFactory.newLatLngZoom(it, 15f)
)

// Update the marker position
selectedMarkerState.position = it
// selectedMarkerState.title = ""
}
}

val markerPositionLong = remember { mutableStateOf(null) }

// Assuming you have the route driver's ID available
val routeDriverId = "driver123" // Replace with actual driver ID
val currentUserId = FirebaseAuth.getInstance().currentUser?.uid

// Start the location service
LaunchedEffect(Unit) {
if (ActivityCompat.checkSelfPermission(
context,
Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED
) {
startLocationService(context)
} else {
requestPermissionLauncher.launch(Manifest.permission.ACCESS_FINE_LOCATION)
}
}

var locationUpdates by remember { mutableStateOf(null) }
val pleaseMarkerState = rememberMarkerState()

val MarkerStateRemember2 = remember { mutableStateOf(null) }

DisposableEffect(Unit) {
val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
intent?.let {
val latitude = it.getDoubleExtra("latitude", 0.0)
val longitude = it.getDoubleExtra("longitude", 0.0)

Log.d("LocationReceiver", "Received Lat: $latitude, Lng: $longitude")

// Update the locationUpdates state with the new LatLng
locationUpdates = LatLng(latitude, longitude)

}
}
}
val filter = IntentFilter("LOCATION_UPDATE")
context.registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED)

onDispose {
context.unregisterReceiver(receiver)
}
}

// Using a Box to stack the Card on top of the GoogleMap
Box(
modifier = Modifier
.fillMaxSize()
) {
GoogleMap(
cameraPositionState = cameraPositionState,
properties = mapProperties,
onMapLoaded = {
// Set up the marker after the map is loaded
var markerPosition = LatLng(-1.2257693, 36.886121)
val markerOptions = MarkerOptions()
.position(markerPosition)
.title("Nairobi")
.snippet("Marker in Nairobi")
.draggable(true)
},
onMapLongClick = { latLng ->
// Add a new MarkerState to the list with the clicked position
markerStatesRoute.add(latLng)
}
) {
// User Live location Marker
Marker(
state = liveLocationMarkerState,
title = "Current Location",
snippet = "This is your current background location",
icon = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)
)

// Selected Place on Map
Marker(
state = selectedMarkerState,
title = "Destination Location",
snippet = "Destination location (for now)",
icon = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)
)

markerStatesRoute.forEach { stop ->
stop?.let { rememberMarkerState(position = it) }?.let {
Marker(
state = it,
title = "Bus Stop",
snippet = "This is a bus Stop",
icon = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)
// Use a custom icon
)
}
}



Подробнее здесь: https://stackoverflow.com/questions/789 ... at-point-i
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Android»