Skip to content

Exercise 2: Terra Draw implementation with UI interactions

Let's create a basic Terra Draw setup with more modes and UI buttons. Update your src/routes/+page.svelte:

Add point, line and polygon modes

Here, we can add basic point, linestring, polygon modes with buttons and clear button to remove all features.

Firstly, import TerraDrawPointMode, TerraDrawLineStringMode and TerraDrawPolygonMode in script tag.

Then, declare draw variable. Using $state(), the variable becomes reactive.

import {
    TerraDraw,
    TerraDrawPointMode,
    TerraDrawLineStringMode,
    TerraDrawPolygonMode
} from 'terra-draw';

let draw: TerraDraw | undefined = $state();

Then, remove draw.setMode("rectangle"); from the last section.

onMount(() => {
    map.once('load', () => {
        // Start drawing
        draw.start();
-        draw.setMode("rectangle");
    })
})

Add methods

Add two methods in the last of script tag.

const handleModeClick = (mode: string) => {
    draw?.setMode(mode);
};

const handleClearClick = () => {
    draw?.clear()
};

Add buttons

Add buttons to HTML section of component

<aside class="sidebar">
    <!-- Use this space for adding additional elements for workshop -->
    <button onclick={() => handleModeClick('point')}>Point</button>
    <button onclick={() => handleModeClick('linestring')}>Line</button>
    <button onclick={() => handleModeClick('polygon')}>Polygon</button>
    <button onclick={handleClearClick}>Clear</button>
</aside>

When a mode button is clicked, handleModeClick function is called and set a corresponding mode to draw instance.

You can draw a point, a line and a polygon after clicking the button. Click clear button, you can remove all features.

Basic example with Point, Line and Polygon
Figure 1: Basic example with Point, Line and Polygon

Testing Your Implementation

  1. Save your changes and the Vite development server should automatically reload
  2. Open your browser to http://localhost:5173
  3. Test drawing - click corresponding buttons to create points, lines and polygons
  4. Remove features - click clear button to remove features.

If you have time, please also try to add other Terra Draw modes to the example.

Example code

The above example code is available at example/with-point-line-polygon branch.

What's Next?

Now you can add / remove points, lines and polygons. Let's do learn how to select a feature and modify them next.