Load selection state with Waygo.js

This example demonstrates how to initialize a Waygo MapView into the selection state using the Waygo.js library. The selection state enables a subset of features to be made selectable on the map, based on a set of inputted criteria.

This approach gives you full control over the map behavior and allows for custom interactions.

How it works

When using Waygo.js to initialize a map with selection state, you add the initialState and initialStateData properties to your MapView configuration:

const map = new waygomaps.MapView({
    container: 'map',
    sourceId: 'your-map-2025',
    initialState: 'selection',
    initialStateData: {
        criteria: { type: 'booth', size: '10x10' },
        multiSelect: true,
    }
});

Example: Load a map in selection mode for any booth feature

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Map with Selection State</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/waygo-maps@1.1.9/dist/style.css">
    <script src="https://cdn.jsdelivr.net/npm/waygo-maps@1.1.9/dist/bundle.js"></script>
    <style>
        body { margin: 0; padding: 0; }
        #map { position: absolute; top: 0; left: 0; width: 100%; height: 100%; overflow: hidden; }
    </style>
</head>
<body>
    <div id="map"></div>
    <script>
        waygomaps.setApiKey("23rh24f3UHR2Hadsoijj1w32i2Rr3h3lhL2k343l420dcaa");

        const map = new waygomaps.MapView({
            container: 'map',
            sourceId: 'c9d01414d1594f12b50d90bac9d4b3fb.expo-expo-2024.PmemisplTIOErumFETKoYw',
            defaultControls: true,
            initialState: 'selection',
            initialStateData: {
                criteria: { type: 'booth' },
                multiSelect: true,
            }
        });
    </script>
</body>
</html>

Configuration Options

initialState

Set to 'selection' to initialize the map in selection mode with pre-selected items.

initialStateData

An object containing the selection configuration:

{
    criteria: { type: 'booth', size: ['10x10', '20x10'] },  // Selection criteria
    multiSelect: true,                              // Allow multiple selections
}

Selection Criteria Format

The criteria object defines what items should be made selectable in the selections state. Each map feature can be tagged with any data, and the criteria here can be used to filter out the unselectable features in any context.

Only features that fit all the provided criteria will be considered to be selectable. Common criteria include:

Criteria with Single Options

{
    criteria: { type: 'booth', size: '10x10' },
}

Criteria with Varying Options

{
    criteria: { type: 'booth', size: ['10x10', '20x20'] },
}

Complex Criteria

{
    criteria: { 
        type: 'booth', 
        size: ['10x10', '20x20'],
        amenities: ['power', 'internet'],
        location: 'main-hall'
    },
}

Event Handling

You can listen for selection changes and other map events. The most important event for selection state is selection:changed since it broadcasts the most up-to-date list of selected content on the map, whenever new selections or deselections take place.

Selection Events

Events are triggered when a user interacts with the map in selection state. Events can include the following:

  • Name
    selection:changed
    Description

    Occurs when the selection changes (items added or removed). Provides the complete current selection state.

  • Name
    selection:featureSelected
    Description

    Occurs when a single feature is selected by the user.

  • Name
    selection:featureDeselected
    Description

    Occurs when a single feature is deselected by the user.

Listening to selection events

Listen to any of these events by subscribing to the event you're interested in:

// Listen to overall selection changes
mapView.on('selection:changed', (data) => {
    const { selectedContent, selectionCount } = data;
    console.log('Selection changed:', selectedContent, selectionCount);
});

// Listen to individual feature selection
mapView.on('selection:featureSelected', (data) => {
    console.log('Feature selected:', data);
});

// Listen to individual feature deselection
mapView.on('selection:featureDeselected', (data) => {
    console.log('Feature deselected:', data);
});

selection:changed event data

The selection:changed event provides two key pieces of data:

  • selectionCount: The number of currently selected items
  • selectedContent: An array of objects containing detailed information about each selected item

Each item in selectedContent contains:

  • feature_id: The unique identifier of the feature
  • name: The display name of the feature
  • All fields from the feature's feature.properties are copied here as additional fields

selection:featureSelected and selection:featureDeselected event data

Both events return the GeoJSON feature as is, which includes:

  • id: The GeoJSON feature identifier
  • type: Always 'Feature' for these events
  • properties: Contains detailed feature properties
  • geometry: Geographic information about the feature
  • Additional internal properties

Integration with Reservations API

The selection events provide all the data needed to facilitate a booking or reservation flow using the Reservations API.

Key Data for Reservations

From the selection:changed event, you can extract:

  • Feature IDs: data.selectedContent[].feature_id - Required for the reservations API
  • Feature Names: data.selectedContent[].name - Useful for user confirmation
  • Additional Properties: data.selectedContent[].{PROPERTY_NAME} - Can include size, location, amenities, etc.
// Example: Extract feature IDs for reservation
mapView.on('selection:changed', (data) => {
    const featureIds = data.selectedContent.map(item => item.feature_id);
    console.log('Selected features for reservation:', featureIds);
    
    // Send to your backend to call the Reservations API
    // POST /reservations/v1/{map_id}/{map_view_id}
    // Body: { feature_ids: featureIds, data: {...} }
});

Advanced Usage

Working with Selection State

You can programmatically check and work with the current selection state:

// Get all currently selected features
const selectedFeatures = mapView.getConfirmedSelectionFeatures();
console.log('Currently selected features:', selectedFeatures);

// Check if a specific feature is selected
const isSelected = mapView.isFeatureSelected('booth-101');
console.log('Is booth-101 selected?', isSelected);

Integration with State Management

For React applications, you can integrate with state management libraries:

const [selectedItems, setSelectedItems] = useState([]);

useEffect(() => {
    mapView.on('selection:changed', (data) => {
        setSelectedItems(data.selectedContent || []);
    });
}, []);

Best Practices

  1. Set API Key First - Always call waygomaps.setApiKey() before creating a MapView
  2. Handle Errors - Wrap map initialization in try-catch blocks
  3. Cleanup Resources - Remove event listeners and destroy map instances when components unmount
  4. Test Criteria - Ensure your selection criteria matches available options in your map
  5. Responsive Design - Use CSS to make your map container responsive
  6. Performance - Consider using useMemo for expensive map configurations in React