JavaScript Choropleth Map Example

Demonstrates how to create a JavaScript Choropleth map, a type of thematic map where areas are shaded or patterned in proportion to the value of a variable being represented, using our FastTriangleRenderableSeries.

New South Wales - 8,511,151 Victoria - 7,012,962 Queensland - 5,608,666 Western Australia - 2,981,752 South Australia - 1,882,722 Tasmania - 575,959 Australian Capital Territory - 475,644 Northern Territory - 255,559

Fullscreen

Edit

 Edit

Docs

drawExample.ts

index.html

vanilla.ts

theme.ts

australiaData.ts

helpers.ts

Copy to clipboard
Minimise
Fullscreen
1import {
2    ZoomExtentsModifier,
3    ZoomPanModifier,
4    NumericAxis,
5    SciChartSurface,
6    NumberRange,
7    XyDataSeries,
8    ETriangleSeriesDrawMode,
9    FastTriangleRenderableSeries,
10    MouseWheelZoomModifier,
11    FastBubbleRenderableSeries,
12    EllipsePointMarker,
13    XyzDataSeries,
14    IPointMetadata,
15    EHorizontalTextPosition,
16    Thickness,
17    EVerticalTextPosition,
18    FastLineRenderableSeries,
19} from "scichart";
20
21import { appTheme } from "../../../theme";
22
23import {
24    getMinMax,
25    interpolateColor,
26    keyData,
27    australiaData,
28    preserveAspectRatio,
29} from "./helpers";
30
31import { australianCities } from "./australiaData";
32
33type Keytype = "population" | "population_density" | "area_km2";
34
35const dataArray: { name: string; areaData: number[][] }[] = [];
36const outlines: number[][][] = [];
37
38function setMapJson(mapJson: any) {
39    mapJson.forEach((d: any) => {
40        outlines.push(d.outline);
41        dataArray.push({ name: d.name, areaData: d.areaData });
42    });
43}
44
45export const drawExample = async (rootElement: string | HTMLDivElement) => {
46    // Create a SciChartSurface
47    const { wasmContext, sciChartSurface } = await SciChartSurface.create(rootElement, {
48        theme: appTheme.SciChartJsTheme,
49    });
50
51    const growBy = new NumberRange(0.1, 0.1);
52
53    sciChartSurface.xAxes.add(new NumericAxis(wasmContext, { growBy, isVisible: true }));
54    sciChartSurface.yAxes.add(new NumericAxis(wasmContext, { growBy, isVisible: true }));
55
56    const xAxis = sciChartSurface.xAxes.get(0);
57    const yAxis = sciChartSurface.yAxes.get(0);
58
59    let firsStime = true;
60
61    const setMap = (key: Keytype) => {
62        sciChartSurface.renderableSeries.clear(true);
63
64        const [min, max] = getMinMax(key, australiaData);
65
66        const series = dataArray.map((d, i) => {
67            const dataSeries = new XyDataSeries(wasmContext, {
68                xValues: d.areaData.map((p) => p[0]),
69                yValues: d.areaData.map((p) => p[1]),
70            });
71
72            const triangleSeries = new FastTriangleRenderableSeries(wasmContext, {
73                dataSeries: dataSeries,
74                drawMode: ETriangleSeriesDrawMode.List,
75                fill: interpolateColor(min, max, keyData[d.name][key]),
76                opacity: 0.9,
77            });
78
79            return triangleSeries;
80        });
81
82        sciChartSurface.renderableSeries.add(...series);
83
84        // outline
85        const outlinesSC = outlines.map((outline) => {
86            const xVals = outline.map((d) => d[0]);
87            const yVals = outline.map((d) => d[1]);
88
89            //FastMountainRenderableSeries
90            const lineSeries = new FastLineRenderableSeries(wasmContext, {
91                dataSeries: new XyDataSeries(wasmContext, {
92                    xValues: xVals,
93                    yValues: yVals,
94                }),
95                stroke: appTheme.DarkIndigo,
96                strokeThickness: 2,
97                opacity: 1,
98            });
99
100            return lineSeries;
101        });
102
103        sciChartSurface.renderableSeries.add(...outlinesSC);
104
105        // cities
106        const cLongitude = australianCities.map((d) => d.longitude);
107        const clatitude = australianCities.map((d) => d.latitude);
108        const cSize = australianCities.map((d) => 5);
109        const cMetadata = australianCities.map((d) => d) as unknown as IPointMetadata[];
110
111        const citiesSeries = new FastBubbleRenderableSeries(wasmContext, {
112            pointMarker: new EllipsePointMarker(wasmContext, {
113                width: 64,
114                height: 64,
115                fill: appTheme.ForegroundColor,
116                strokeThickness: 0,
117            }),
118            dataSeries: new XyzDataSeries(wasmContext, {
119                xValues: cLongitude,
120                yValues: clatitude,
121                zValues: cSize,
122                metadata: cMetadata,
123            }),
124            dataLabels: {
125                verticalTextPosition: EVerticalTextPosition.Above,
126                horizontalTextPosition: EHorizontalTextPosition.Right,
127                style: {
128                    fontFamily: "Arial",
129                    fontSize: 14,
130                    padding: new Thickness(0, 0, 3, 3),
131                },
132                color: "#EEE",
133                metaDataSelector: (md) => {
134                    const metadata = md as unknown as { name: string };
135                    return metadata.name.toString();
136                },
137            },
138        });
139        sciChartSurface.renderableSeries.add(citiesSeries);
140
141        if (firsStime) {
142            sciChartSurface.zoomExtents();
143            firsStime = false;
144        }
145
146        sciChartSurface.preRender.subscribe(() => {
147            const result = preserveAspectRatio(
148                sciChartSurface.viewRect.width,
149                sciChartSurface.viewRect.height,
150                xAxis.visibleRange.min,
151                xAxis.visibleRange.max,
152                yAxis.visibleRange.min,
153                yAxis.visibleRange.max
154            );
155
156            xAxis.visibleRange = new NumberRange(result.minVisibleX, result.maxVisibleX);
157            yAxis.visibleRange = new NumberRange(result.minVisibleY, result.maxVisibleY);
158        });
159    };
160
161    // Add zoom/pan controls
162    sciChartSurface.chartModifiers.add(
163        new ZoomExtentsModifier(),
164        new ZoomPanModifier({ enableZoom: true }),
165        new MouseWheelZoomModifier()
166    );
167
168    return { wasmContext, sciChartSurface, setMap, setMapJson };
169};
170

Map Example - JavaScript

Overview

This JavaScript example demonstrates how to create an interactive map of Australia using SciChart.js. It visualizes geographic data with FastTriangleRenderableSeries for terrain coloring and FastLineRenderableSeries for state outlines.

Technical Implementation

The implementation uses triangulation to convert geographic coordinates into renderable triangles with ETriangleSeriesDrawMode.List mode. Data is loaded from predefined arrays and styled based on population density metrics. The chart includes interactive modifiers like ZoomPanModifier for navigation. This example fetches australiaConverted.json from server. australiaConverted.json is array of objects and each object contains 'name', 'outline' and 'areaData'.

  • name is string that contains name of the location

  • outline is array of arrays that represent longitude and latitude of points that represent outline of area

  • areaData is array of arrays that represent series of coordinate points that form triangles used by SciChart's FastTriangleRenderableSeries to create shapes that represent area

areaData is generated using poly2tri - https://github.com/r3mi/poly2tri.js, a 2D constrained Delaunay triangulation library from GeoJSON representation of Australia map

Features and Capabilities

The example shows dynamic recoloring of states based on selected metrics (population, area, or density) using a custom interpolation function. City markers are displayed using FastBubbleRenderableSeries with data labels.

Integration and Best Practices

The implementation follows JavaScript best practices with async chart initialization and proper surface disposal. The aspect ratio preservation logic ensures correct map proportions during resizing.

javascript Chart Examples & Demos

See Also: Charts added in v4 (16 Demos)

JavaScript Histogram Chart | Javascript Charts | SciChart.js

JavaScript Histogram Chart

Create a JavaScript Histogram Chart with custom texture fills and patterns. Try the SciChart.js library for seamless integration today.

JavaScript Gantt Chart | Javascript Charts | SciChart.js Demo

JavaScript Gantt Chart Example

Build a JavaScript Gantt Chart with SciChart. View the demo for horizontal bars, rounded corners and data labels to show project timelines and task completion.

JavaScript Multi-Layer Map | Javascript Charts | SciChart.js

JavaScript Multi-Layer Map Example

Create a JavaScript Multi-Layer Map Example, using FastTriangleRenderableSeries with GeoJSON data-points using a constrained delaunay triangulation algorithm.

JavaScript Animated Bar Chart | Javascript Charts | SciChart.js

JavaScript Animated Bar Chart Example

Bring annual comparison data to life with the JavaScript Animated Bar Chart example from SciChart. This demo showcases top 10 tennis players from 1990 to 2024.

JavaScript Vector Field Plot | Javascript Charts | SciChart.js

JavaScript Vector Field Plot

View the JavaScript Vector Field Plot example from SciChart, including dynamic vector generation, gradient-colored segments, and interactive zoom/pan. Try demo.

JavaScript Waterfall Chart | Bridge Chart | SciChart.js

JavaScript Waterfall Chart | Bridge Chart

Build a JavaScript Waterfall Chart with dynamic coloring, multi-line data labels and responsive design. Try SciChart.js for seamless integration today.

JavaScript Box Plot Chart | Javascript Charts | SciChart.js Demo

JavaScript Box Plot Chart

Try the JavaScript Box-Plot Chart examples with developer-friendly chart lifecycle management, dynamic sub-surface positioning, and custom styling.

JavaScript Triangle Series | Triangle Mesh Chart | SciChart

JavaScript Triangle Series | Triangle Mesh Chart

Create JavaScript Triangle Meshes with the Triangle Series from SciChart. This demo supports strip mode, list mode and the drawing of polygons. View the example.

JavaScript Treemap Chart | Javascript Charts | SciChart.js Demo

JavaScript Treemap Chart

Create a JavaScript Treemap Chart to define rectangle positions based on total value. Use SciChart FastRectangleRenderableSeries and d3-hierarchy.js layouts.

NEW!
JavaScript Map Chart with Heatmap overlay | SciChart.js

JavaScript Map Chart with Heatmap overlay

Design a highly dynamic JavaScript Map Chart with Heatmap overlay with SciChart's feature-rich JavaScript Chart Library. Get your free demo today.

Realtime Audio Analyzer Bars Demo | SciChart.js Demo

Realtime Audio Analyzer Bars Demo

Demonstrating the capability of SciChart.js to create a JavaScript Audio Analyzer Bars and visualize the Fourier-Transform of an audio waveform in realtime.

JavaScript Linear Gauges | Javascript Charts | SciChart.js Demo

JavaScript Linear Gauges Example

View the JavaScript Linear Gauge Chart example to combine rectangles & annotations. Create a linear gauge dashboard with animated indicators and custom scales.

NEW!
JavaScript Order of Rendering | Javascript Charts | SciChart.js

JavaScript Order of Rendering Example

The JavaScript Order of Rendering example gives you full control of the draw order of series and annotations for charts. Try SciChart's advanced customizations.

Responsive HTML Annotations | Javascript Charts | SciChart.js

JavaScript Responsive HTML Annotations Example

Build Responsive JavaScript HTML Annotations with SciChart. Use the advanced CSS container queries for responsive text layout and custom design. View demo now.

HTML Annotations and Custom in-chart Controls | SciChart

HTML Annotations and Custom in-chart Controls Example

JavaScript HTML Chart Control example demonstrates advanced HTML annotation integration and how to render HTML components within charts. Try the SciChart demo.

JavaScript Polar Modifiers | Polar Interactivity Modifiers

JavaScript Polar Modifiers | Polar Interactivity Modifiers Demo

Explore SciChart's Polar Interactivity Modifiers including zooming, panning, and cursor tracking. Try the demo to trial the Polar Chart Behavior Modifiers.

SciChart Ltd, 16 Beaufort Court, Admirals Way, Docklands, London, E14 9XL.