Location Sharing

Location sharing allows users to send a static position or share their real-time location with other participants in a channel. Stream Chat supports both static and live location sharing through location attachments.

There are two types of location sharing:

  • Static Location: A one-time location share that does not update over time.
  • Live Location: A real-time location share that updates over time.

The SDK handles location message creation and updates, but location tracking must be implemented by the application using device location services.

Sending static location

Static location sharing allows you to send a message containing a static location.

// Send a static location message.
chatClient.sendStaticLocation(
    cid = "channelType:channelId",
    latitude = -8.0421,
    longitude = -34.9351,
    deviceId = "my-device-id",
).enqueue { /* ... */ }

Starting live location sharing

Live location sharing enables real-time location updates for a specified duration. The SDK manages the location message lifecycle, but your application is responsible for providing location updates.

// Start a live location sharing and automatically stops after 10 minutes.
val tenMinutesFromNow = Date().apply { time += 10.minutes.inWholeMilliseconds }
chatClient.startLiveLocationSharing(
    cid = "channelType:channelId",
    latitude = -8.0421,
    longitude = -34.9351,
    deviceId = "my-device-id",
    endAt = tenMinutesFromNow,
).enqueue { /* ... */ }

Stopping live location sharing

You can stop live location sharing for a specific message using the message controller:

// Stop a live location sharing.
chatClient.stopLiveLocationSharing(
    messageId = "live-location-message-id",
    deviceId = "my-device-id",
).enqueue { /* ... */ }

Updating live location

Your application must implement location tracking and provide updates to the SDK. The SDK handles updating all the current user’s active live location messages and provides a throttling mechanism to prevent excessive API calls.

// Query user's active live locations (call only once when user is connected).
chatClient.queryActiveLocations().enqueue { /* ... */ }

// Listen for changes in current user's active live locations.
chatClient.globalStateFlow
    .flatMapLatest { it.currentUserActiveLiveLocations }
    .onEach { userActiveLiveLocations ->
        if (userActiveLiveLocations.isEmpty()) {
            // Stop receiving device location updates if there's no active live locations.
        } else {
            // Start receiving device location updates (check for location permissions).
        }
    }
    .launchIn(coroutineScope)

// Update live location when device location changes.
for (deviceLocation in result.locations) {
    userActiveLiveLocations
        .filterNot { it.endAt?.before(Date()) ?: false } /// Filter out expired locations
        .forEach { activeLiveLocation ->
            chatClient.updateLiveLocation(
                messageId = activeLiveLocation.messageId,
                latitude = deviceLocation.latitude,
                longitude = deviceLocation.longitude,
                deviceId = "my-device-id",
            ).enqueue { /* ... */ }
        }
}

Whenever the location is updated, the message will automatically be updated with the new location.

The SDK will also notify your application when it should start or stop location tracking as well as when the active live location messages change.

extension SomeObject: CurrentChatUserControllerDelegate {

    /// Called when the user starts sharing a live location and it wasn't already sharing a live location
    func currentUserControllerDidStartSharingLiveLocation(
        _ controller: CurrentChatUserController
    ) {
        // Start location monitoring (Needs to be implemented by the application)
        startLocationTracking()
    }

    /// Called when all live location sharing stops
    func currentUserControllerDidStopSharingLiveLocation(
        _ controller: CurrentChatUserController
    ) {
        // Stop location monitoring
        stopLocationTracking()
    }

    /// Called when active live location messages change
    func currentUserController(
        _ controller: CurrentChatUserController,
        didChangeActiveLiveLocationMessages messages: [ChatMessage]
    ) {
        // You can use this delegate method to track the active live location messages and
        // if needed render all of them in a UI component or you can use this for finer control
        // when to start or stop tracking locations.
    }

    /// Called when a live location update fails
    func currentUserController(
        _ controller: CurrentChatUserController,
        didFailToUpdateLiveLocation location: SharedLocation,
        with error: Error
    ) {
        // Handle error if needed
    }

}

Events

Whenever a location is created or updated, the following WebSocket events will be sent:

  • message.new: When a new location message is created.
  • message.updated: When a location message is updated.

You can easily check if a message is a location message by checking the message.sharedLocation property. For example, you can use this events to render the locations in a map view.

chatClient.subscribeFor(NewMessageEvent::class, MessageUpdatedEvent::class) { event ->
    /// Check if the event is for the watching channel.
    if ((event as? CidEvent)?.cid == "my-watching-cid") {
        when (event) {
            is NewMessageEvent -> event.message.sharedLocation?.let { location ->
                // Add a new location to the map.
            }
            is MessageUpdatedEvent -> event.message.sharedLocation?.let { location ->
                // Update the existing location in the map.
            }
            else -> Unit
        }
    }
}
© Getstream.io, Inc. All Rights Reserved.