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 TrafficService 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.
Configure the traffic service
Traffic behavior can be customized through the TrafficPreferences instance, accessible via the TrafficService 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:
trafficService.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 of the listener implementation provided to either the startNavigation or startSimulation method.
The snippet below will add a roadblock of 100 meters starting in 10 meters:
NavigationService().setNavigationRoadBlock(100, 10);
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 a ETrafficOnlineRestrictions enum.
For example, in order to check if traffic events are available for a certain geographic position:
Coordinates coords( 50.108, 8.783 );
ETrafficOnlineRestrictions restriction = TrafficService().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.InitFail: Failed to initialize the traffic service.
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 with theerror::KActivationcode. - If a roadblock already exists at the same location where the user attempts to add a new one, the operation will fail with the
error::KExistcode. - If the input parameters are invalid (e.g., expireTime is later than startTime, missing id, or invalid coordinates/area object), the addition will fail with the
error::KInvalidInputcode. - If a roadblock with the same id already exists, the addition will fail with the
error::KInUsecode.
Add an area-based persistent roadblock
The addPersistentRoadblock method specialized for areas 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 along with theKNoErrorcode. - If the addition fails, the method returns a default
TrafficEventand an appropriateerrorcode, indicating the reason for the failure.
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:
auto area = RectangleGeographicArea( {46.764942, 7.122563}, {46.762031, 7.127992});
auto now = Time::getUniversalTime();
LargeInteger oneHour = 3600 * 1000; // milliseconds in one hour
auto result = TrafficService().addPersistentRoadblock(
area,
now,
now + oneHour,
ERouteTransportMode::RTM_Car,
"test_id");
if (result.second == KNoError) {
GEM_INFO_LOG("The addition was successful");
TrafficEvent event = result.first;
} else {
GEM_INFO_LOG("The addition failed with error code %d", result.second);
}
Add a path-based persistent roadblock
The addPersistentRoadblock method specialized for coordinates is used to add path-based user roadblocks. It accepts a list of Coordinate 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:
CoordinatesList coords;
coords.push_back( Coordinates( 45.64695, 25.62070 ) );
auto now = Time::getUniversalTime();
LargeInteger oneHour = 3600 * 1000; // milliseconds in one hour
auto result = TrafficService().addPersistentRoadblock(
coords,
now,
now + oneHour,
ERouteTransportMode::RTM_Car,
"test_id"
);
if (result.second == KNoError) {
GEM_INFO_LOG("The addition was successful");
TrafficEvent event = result.first;
} else {
GEM_INFO_LOG("The addition failed with error code %d", result.second);
}
In addition to the scenarios described above, the 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 default
TrafficEventalong with theerror::KNotFounderror code. - Route Computation Failed: If multiple coordinates are provided but a valid route cannot be computed between them, the method will return default
TrafficEventand theerror::KNoRouteerror code.
Add an anti-area persistent roadblock
If a region contains a persistent roadblock, the user may wish to whitelist a specific sub-area within the larger restricted zone to allow routing and navigation through that portion. This can be achieved using the addPersistentAntiRoadblock method with area, which accepts the same arguments as the addPersistentRoadblock method described above.
This functionality enables fine-grained control over blocked regions by allowing exceptions within otherwise restricted areas.
Get all user-defined persistent roadblocks
The getPersistentRoadblocks getter provided by the TrafficService provides the list of persistent roadblocks.
The following snippet iterates through all persistent roadblocks - both path-based and area-based - and prints their unique identifiers.
auto roadblocks = TrafficService().getPersistentRoadblocks();
for (auto roadblock : roadblocks)
{
GEM_INFO_LOG("%s", 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
To get both path-based and area-based roadblocks if the identifier is known use the getPersistentRoadblock method.
This method takes the identifier string as argument and returns null if the event could not be found or the event if it exists.
auto event = TrafficService().getPersistentRoadblock("unique_id");
if (!event.isDefault())
{
GEM_INFO_LOG("Event was found");
} else
{
GEM_INFO_LOG("Event does not exist");
}
Remove user-defined roadblocks
Remove persistent user-defined roadblock by id
Use the removePersistentRoadblock method with string to remove a roadblock if the identifier is known.
auto error = TrafficService().removePersistentRoadblock("identifier");
if (error == KNoError){
GEM_INFO_LOG("Removal succeded");
} else {
GEM_INFO_LOG("Removal failed with error code %d", error);
}
The method returns KNoError if the roadblock was removed and error::KNotFound if no roadblock was found with the given id.
This method work both for path-based and area-based roadblocks.
Remove persistent user-defined roadblock by coordinates
Use the removePersistentRoadblock method with coordinates to remove a path-based roadblock by providing the method with the first coordinate of the roadblock to be removed.
auto error = TrafficService().removePersistentRoadblock(coords);
if (error == KNoError){
GEM_INFO_LOG("Removal succeded");
} else {
GEM_INFO_LOG("Removal failed with error code %d", error);
}
The method returns KNoError if the roadblock was removed and error::KNotFound if no roadblock was found starting with the given coordinate.
Remove all user-defined persistent roadblocks
Use the removeAllPersistentRoadblocks method to delete all existing user-defined roadblocks.
Get preview of a path-based user-defined roadblock
Before adding a persistent user roadblock, the user can preview the path using an intermediary list of coordinates generated between two positions. This functionality is provided by the getPersistentRoadblockPathPreview method, which helps visualize the intended roadblock on the map.
This method takes as arguments:
UserRoadblockPathPreviewCoordinatefrom- The starting point of the roadblock. Can be obtained:- from a
Coordinatesobject. - returned by the
getPersistentRoadblockPathPreviewmethod to allow daisy-chaining multiple segments.
- from a
Coordinatesto- The ending point of the roadblock.ERouteTransportModetransportMode- The transport mode (e.g., car, bicycle, pedestrian) to be used for the roadblock preview and calculation.
The method returns a tuple containing:
List<Coordinates>- A list of intermediate coordinates forming the preview path. This list can be used to render a polyline or marker path on the map.UserRoadblockPathPreviewCoordinate- The updatedendcoordinate, which can be reused as thefromargument to preview or chain additional segments.error- Error code of the operation. This may include the same error codes returned byaddPersistentRoadblock. The rest of the return values are not valid if the error is not success.
For example, in oder to get the preview of a user-defined path-based roadblock between two Coordinate objects:
Coordinates startCoordinates = ...
Coordinates endCoordinates = ...
UserRoadblockPathPreviewCoordinate previewStart;
previewStart.coord = startCoordinates;
auto result =
TrafficService().getPersistentRoadblockPathPreview(
previewStart,
endCoordinates,
ERouteTransportMode::RTM_Car
);
auto coordinates = std::get<0>( result );
previewStart = std::get<1>(result);
auto previewError = std::get<2>(result);
if (previewError != KNoError) {
GEM_INFO_LOG("Error %d during preview calculation", previewError);
} else {
// Draw the path on the UI
Path previewPath(coordinates);
mapView->preferences().paths().add(previewPath);
// If the user is happy with the roadblock preview,
// the roadblock can be added using addPersistentRoadblockByCoordinates
}
Persistent roadblock listener
The Magic Lane SDK for C++ 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 callback provide the activated/expired List<TrafficEvent>.
Implement IPersistentRoadblockListener listener and set it into the TrafficService:
class MyPersistentRoadblockListener : public IPersistentRoadblockListener
{
public:
void onRoadblocksExpired(const TrafficEventList& eventList) override
{
// Do something with the events
}
void onRoadblocksActivated(const TrafficEventList& eventList) override
{
// Do something with the events
}
};
auto listener = StrongPointerFactory<MyPersistentRoadblockListener>();
TrafficService().setPersistentRoadblockListener(listener);