Roadblocks
A roadblock is a user-defined restriction applied to a specific road segment or geographic area, used to reflect traffic disruptions such as construction, closures, or areas to avoid.
It influences route planning by marking certain paths or zones as unavailable for navigation.
Roadblocks can be path-based (defined by a sequence of coordinates) or area-based (covering a geographic region), and may be either temporary or persistent, depending on their intended duration. Persistent roadblocks remain after a SDK uninitialization. Temporary roadblocks are short-lived.
The primary entity responsible for representing roadblocks is the TrafficEvent class. Check the Traffic Events guide for more details.
Roadblocks are mainly managed through the Traffic class.
While some roadblocks are provided in real time by online data from Magic Lane servers, users can also define their own user roadblocks to customize routing behavior.
If the applied style includes traffic data and traffic display is enabled (MapViewPreferences.setTrafficVisibility is set to true), a visual indication of the blocked portion will appear on the map, highlighted in red.
Adding/removing user roadblocks affects only the current user and does not impact other users' routes. To create reports that are visible to all users, refer to the Social Reports guide.
Configure the traffic service
Traffic behavior can be customized through the TrafficPreferences instance, accessible via the Traffic class. The TrafficPreferences class provides the useTraffic property, which defines how traffic data should be applied during routing and navigation.
The ETrafficUsage enum offers the following configuration options:
| Value | Description |
|---|---|
UseNone | Disables all traffic data usage. |
UseOnline | Uses both online and offline traffic data (default setting). |
UseOffline | Uses only offline traffic data, including user-defined roadblocks. |
For example, in order to set allow only offline usage the following line can be used:
- Kotlin
- Java
val traffic = Traffic()
traffic.preferences?.useTraffic = ETrafficUsage.UseOffline
Traffic traffic = new Traffic();
TrafficPreferences preferences = traffic.getPreferences();
if (preferences != null) {
preferences.setUseTraffic(ETrafficUsage.UseOffline);
}
Add a temporary user roadblock while in navigation
A roadblock can be added to bypass a portion of the route for a specified distance. Once the roadblock is applied, the route will be recalculated, and the updated route will be returned via the onRouteUpdated callback provided to either the startNavigation or startSimulation method.
The snippet below will add a roadblock of 100 meters starting from the current position:
- Kotlin
- Java
val navigationService = NavigationService()
navigationService.setNavigationRoadBlock(100)
NavigationService navigationService = new NavigationService();
navigationService.setNavigationRoadBlock(100);
Roadblocks added through the setNavigationRoadBlock method provided by the NavigationService only affect the ongoing navigation.
Check if a geographic position has traffic information
The getOnlineServiceRestrictions method can be used. It takes a Coordinates object as argument and returns an integer containing flags from the ETrafficOnlineRestrictions enum.
For example, in order to check if traffic events are available for a certain geographic position:
- Kotlin
- Java
val coords = Coordinates(50.108, 8.783)
val traffic = Traffic()
val restrictions = traffic.getOnlineServiceRestrictions(coords)
Coordinates coords = new Coordinates(50.108, 8.783);
Traffic traffic = new Traffic();
int restrictions = traffic.getOnlineServiceRestrictions(coords);
The ETrafficOnlineRestrictions enum provides the following values:
Settings: Online traffic is disabled in theTrafficPreferencesobject.Connection: No internet connection is available.NetworkType: Not allowed on extra charged networks (e.g., roaming).ProviderData: Required provider data is missing.WorldMapVersion: The world map version is outdated and incompatible. Please update the road map.DiskSpace: Insufficient disk space to download or store traffic data.
Add a user-defined persistent roadblock
To add a persistent user-defined roadblock, the user must provide the following:
- startTime : the timestamp indicating when the roadblock becomes active.
- expireTime : the timestamp indicating when the roadblock is no longer in effect.
- transportMode : the specific mode of transport affected by the roadblock.
- id : a unique string ID for the roadblock.
- coords/area : either:
- a list of coordinates (for path-based roadblocks), or
- a geographic area (for area-based roadblocks).
When a user-defined roadblock is added, it will affect routing and navigation between the specified startTime and expireTime. Once the expireTime is reached, the roadblock is automatically removed without any user intervention.
The following conditions apply when adding a roadblock:
- If roadblocks are disabled in the
TrafficPreferencesobject, the addition will fail and returnnull. - If a roadblock already exists at the same location where the user attempts to add a new one, the operation will fail and return
null. - If the input parameters are invalid (e.g., expireTime is later than startTime, missing id, or invalid coordinates/area object), the addition will fail and return
null. - If a roadblock with the same id already exists, the addition will fail and return
null.
Add a area-based persistent roadblock
The addPersistentRoadblock method with a GeographicArea parameter is used to add area-based user roadblocks. It accepts a GeographicArea object which represents the area to be avoided.
The method returns:
- If the addition is successful, the method returns the newly created
TrafficEventinstance. - If the addition fails, the method returns
null.
For example, adding a area-based user-defined persistent roadblock on a given area, starting from now and available for 1 hour which affects cars can be done in the following way:
- Kotlin
- Java
val topLeft = Coordinates(46.764942, 7.122563)
val bottomRight = Coordinates(46.762031, 7.127992)
val area = RectangleGeographicArea(topLeft, bottomRight)
val startTime = Time.getUniversalTime()
val endTime = Time.getUniversalTime()?.apply { minute += 60 }
val traffic = Traffic()
val trafficEvent = if (startTime != null && endTime != null) {
traffic.addPersistentRoadblock(
area = area,
startUTC = startTime,
expireUTC = endTime,
transportMode = ERouteTransportMode.Car.value,
id = "test_id"
)
} else null
if (trafficEvent != null) {
println("The addition was successful")
} else {
println("The addition failed")
}
Coordinates topLeft = new Coordinates(46.764942, 7.122563);
Coordinates bottomRight = new Coordinates(46.762031, 7.127992);
RectangleGeographicArea area = new RectangleGeographicArea(topLeft, bottomRight);
Time startTime = Time.getUniversalTime();
Time endTime = Time.getUniversalTime();
Traffic traffic = new Traffic();
TrafficEvent trafficEvent = null;
if (startTime != null && endTime != null) {
endTime.setMinute(endTime.getMinute() + 60);
trafficEvent = traffic.addPersistentRoadblock(
area,
startTime,
endTime,
ERouteTransportMode.Car.getValue(),
"test_id"
);
}
if (trafficEvent != null) {
System.out.println("The addition was successful");
} else {
System.out.println("The addition failed");
}
Add a path-based persistent roadblock
The addPersistentRoadblock method with a CoordinatesList parameter is used to add path-based user roadblocks. It accepts a list of Coordinates objects and supports two modes of operation:
- Single Coordinate: Defines a point-based roadblock. This may result in two roadblocks being created - one for each travel direction.
- Multiple Coordinates: Defines a path-based roadblock, starting at the first coordinate and ending at the last. This is used to restrict access along a specific road segment.
For example, adding a path-based user-defined persistent roadblock on both sides of the matching road, starting from now and available for 1 hour which affects cars can be done in the following way:
- Kotlin
- Java
val coords = arrayListOf(Coordinates(405.847994, 24.956233))
val startTime = Time.getUniversalTime()
val endTime = Time.getUniversalTime()?.apply { minute += 60 }
val traffic = Traffic()
val trafficEvent = if (startTime != null && endTime != null) {
traffic.addPersistentRoadblock(
coords = coords,
startUTC = startTime,
expireUTC = endTime,
transportMode = ERouteTransportMode.Car.value,
id = "test_id"
)
} else null
if (trafficEvent != null) {
println("The addition was successful")
} else {
println("The addition failed")
}
ArrayList<Coordinates> coords = new ArrayList<>();
coords.add(new Coordinates(405.847994, 24.956233));
Time startTime = Time.getUniversalTime();
Time endTime = Time.getUniversalTime();
Traffic traffic = new Traffic();
TrafficEvent trafficEvent = null;
if (startTime != null && endTime != null) {
endTime.setMinute(endTime.getMinute() + 60);
trafficEvent = traffic.addPersistentRoadblock(
coords,
startTime,
endTime,
ERouteTransportMode.Car.getValue(),
"test_id"
);
}
if (trafficEvent != null) {
System.out.println("The addition was successful");
} else {
System.out.println("The addition failed");
}
The method returns the result in a similar way to the area-based method.
In addition to the scenarios described above, the path-based addPersistentRoadblock method may also fail in the following cases:
- No Suitable Road Found: If a valid road cannot be identified at the specified coordinates, or if no road data (online or offline) is available for the given location, the method will return
null. - Route Computation Failed: If multiple coordinates are provided but a valid route cannot be computed between them, the method will return
null.
Add an anti-area persistent roadblock
The Android SDK does not currently provide a specific method for creating anti-area roadblocks. This functionality may be available in future versions of the SDK.
Get all user-defined persistent roadblocks
The persistentRoadblocks property provided by the Traffic class provides the list of persistent roadblocks.
The following snippet iterates through all persistent roadblocks - both path-based and area-based - and prints their descriptions.
- Kotlin
- Java
val traffic = Traffic()
val roadblocks = traffic.persistentRoadblocks
roadblocks?.forEach { roadblock ->
if (roadblock.isUserRoadblock())
println(roadblock.description)
}
Traffic traffic = new Traffic();
List<TrafficEvent> roadblocks = traffic.getPersistentRoadblocks();
if (roadblocks != null) {
for (TrafficEvent roadblock : roadblocks) {
if (roadblock.isUserRoadblock()) {
System.out.println(roadblock.getDescription());
}
}
}
All user-defined roadblocks that are currently active or scheduled to become active are returned. Expired roadblocks are automatically removed.
Get user-defined persistent roadblocks
The Android SDK does not currently provide a specific method to get a roadblock by ID. You can iterate through the persistentRoadblocks list to find a specific roadblock by comparing IDs or other properties.
- Kotlin
- Java
val traffic = Traffic()
val roadblocks = traffic.persistentRoadblocks
val targetId = "unique_id"
val event = roadblocks?.find { it.description == targetId }
if (event != null) {
println("Event was found")
} else {
println("Event does not exist")
}
Traffic traffic = new Traffic();
List<TrafficEvent> roadblocks = traffic.getPersistentRoadblocks();
String targetId = "unique_id";
TrafficEvent event = null;
if (roadblocks != null) {
for (TrafficEvent rb : roadblocks) {
if (targetId.equals(rb.getDescription())) {
event = rb;
break;
}
}
}
if (event != null) {
System.out.println("Event was found");
} else {
System.out.println("Event does not exist");
}
Remove user-defined roadblocks
Remove persistent user-defined roadblock by id
Use the removePersistentRoadblock method with a string ID to remove a roadblock if the identifier is known.
- Kotlin
- Java
val traffic = Traffic()
val errorCode = traffic.removePersistentRoadblock("identifier")
if (errorCode == GemError.Success) {
println("Removal succeeded")
} else {
println("Removal failed with error code $errorCode")
}
Traffic traffic = new Traffic();
int errorCode = traffic.removePersistentRoadblock("identifier");
if (errorCode == GemError.Success) {
System.out.println("Removal succeeded");
} else {
System.out.println("Removal failed with error code " + errorCode);
}
The method returns GemError.Success if the roadblock was removed and GemError.NotFound if no roadblock was found with the given id.
This method works both for path-based and area-based roadblocks.
Remove persistent user-defined roadblock by coordinates
Use the removePersistentRoadblock method with a Coordinates parameter to remove path-based roadblocks by providing the method with the first coordinate of the roadblock to be removed.
- Kotlin
- Java
val traffic = Traffic()
val errorCode = traffic.removePersistentRoadblock(coords)
if (errorCode == GemError.Success) {
println("Removal succeeded")
} else {
println("Removal failed with error code $errorCode")
}
Traffic traffic = new Traffic();
int errorCode = traffic.removePersistentRoadblock(coords);
if (errorCode == GemError.Success) {
System.out.println("Removal succeeded");
} else {
System.out.println("Removal failed with error code " + errorCode);
}
The method returns GemError.Success if the roadblock was removed and GemError.NotFound if no roadblock was found starting with the given coordinate.
Remove user-defined roadblock given the TrafficEvent
If the TrafficEvent instance is available, it can be removed using the removeUserRoadblock method:
- Kotlin
- Java
val event: TrafficEvent = // ... obtained from somewhere
val traffic = Traffic()
traffic.removeUserRoadblock(event)
TrafficEvent event = // ... obtained from somewhere
Traffic traffic = new Traffic();
traffic.removeUserRoadblock(event);
This method can be used for both persistent and non-persistent roadblocks.
Remove all user-defined persistent roadblocks
Use the removeAllPersistentRoadblocks method to delete all existing user-defined roadblocks.
- Kotlin
- Java
val traffic = Traffic()
traffic.removeAllPersistentRoadblocks()
Traffic traffic = new Traffic();
traffic.removeAllPersistentRoadblocks();
Get preview of a path-based user-defined roadblock
The Android SDK does not currently provide a specific method for generating roadblock path previews. This functionality may be available in future versions of the SDK, or you can implement path preview by using the routing services to calculate routes between coordinates.
Persistent roadblock listener
The Magic Lane SDK for Android also allows users to register for notifications related to persistent roadblocks. These notifications are triggered in the following cases:
- When a roadblock's
startTimebecomes greater than the current time - via theonRoadblocksActivatedcallback - When a roadblock's
endTimebecomes less than the current time - via theonRoadblocksExpiredcallback
These callbacks provide the activated/expired TrafficEventList.
Create a PersistentRoadblockListener instance:
- Kotlin
- Java
val listener = object : PersistentRoadblockListener() {
override fun onRoadblocksActivated(list: TrafficEventList) {
// Do something with the activated events
list.forEach { event ->
println("Roadblock activated: ${event.description}")
}
}
override fun onRoadblocksExpired(list: TrafficEventList) {
// Do something with the expired events
list.forEach { event ->
println("Roadblock expired: ${event.description}")
}
}
}
PersistentRoadblockListener listener = new PersistentRoadblockListener() {
@Override
public void onRoadblocksActivated(TrafficEventList list) {
// Do something with the activated events
for (TrafficEvent event : list) {
System.out.println("Roadblock activated: " + event.getDescription());
}
}
@Override
public void onRoadblocksExpired(TrafficEventList list) {
// Do something with the expired events
for (TrafficEvent event : list) {
System.out.println("Roadblock expired: " + event.getDescription());
}
}
};
Register the listener using the setPersistentRoadblockListener method of the Traffic class:
- Kotlin
- Java
val traffic = Traffic()
traffic.setPersistentRoadblockListener(listener)
Traffic traffic = new Traffic();
traffic.setPersistentRoadblockListener(listener);