← Back to Demo

Interactive World Map - Code Examples

Complete guide to using the Interactive World Map library.

This page shows all configuration options with working code examples. Copy any example and customize it for your needs.

Quick Navigation

1. Basic Setup

Minimal Example

// Include required libraries in HTML
<script src="https://cdn.plot.ly/plotly-2.27.0.min.js"></script>
<script src="interactive-map.js"></script>
<link rel="stylesheet" href="interactive-map.css">

// Create a container in your HTML
<div id="mapContainer"></div>

// Initialize the map
const map = new InteractiveMap('mapContainer', {
  chartTitle: 'My World Map',
  theme: 'light'
});

// Load and render data
await map.loadCountryData('country-data.json');
await map.render();

With Inline Data

const countryData = [
  { country: 'USA', value: 85, name: 'United States' },
  { country: 'CAN', value: 75, name: 'Canada' },
  { country: 'GBR', value: 90, name: 'United Kingdom' },
  { country: 'JPN', value: 95, name: 'Japan' }
];

const map = new InteractiveMap('mapContainer');
await map.loadCountryData(countryData);
await map.render();
Note: Country codes must be ISO-3 format (3-letter codes). Common examples: USA, CAN, GBR, FRA, DEU, JPN, CHN, IND, AUS, BRA.

2. Loading Data

Country Data (Choropleth)

// From JSON file
await map.loadCountryData('country-data.json');

// From array
const data = [
  { 
    country: 'USA',     // Required: ISO-3 code
    value: 85,         // Required: numeric value
    name: 'United States'  // Optional: display name
  }
];
await map.loadCountryData(data);

// From API
const response = await fetch('https://api.example.com/data');
const apiData = await response.json();
await map.loadCountryData(apiData);

Scatter/Marker Data

// Add markers/points on the map
const markers = [
  { 
    lon: -100,           // Required: longitude (-180 to 180)
    lat: 38,             // Required: latitude (-90 to 90)
    size: 120,           // Optional: marker size
    color: '#2678b3',   // Optional: marker color
    label: 'New York'    // Optional: hover label
  },
  { lon: 139, lat: 35, size: 115, label: 'Tokyo' }
];

await map.loadScatterData(markers);

// Or from file
await map.loadScatterData('scatter-data.json');

3. Visual Customization

Themes & Colors

const map = new InteractiveMap('mapContainer', {
  theme: 'light',  // 'light' or 'dark'
  
  // Custom colors for light theme
  colors: {
    light: {
      scale: [
        [0, '#d4e9f5'],  // Min value color (light blue)
        [1, '#2678b3']   // Max value color (dark blue)
      ],
      landDefault: '#f3f7fa',      // Countries without data
      ocean: '#ffffff',            // Ocean/sea color
      scatterDefault: '#2678b3',   // Default marker color
      scatterHighlight: '#ff9800', // Highlighted marker
      borders: 'white'             // Country borders
    }
  }
});

Map Projections

const map = new InteractiveMap('mapContainer', {
  projection: 'miller'  // Options: miller, equirectangular, mercator, natural earth
});

// miller - Balanced flat projection (default, recommended)
// equirectangular - Simple flat grid
// mercator - Navigation-style (enlarges poles)
// natural earth - Curved globe appearance

Size & Layout

const map = new InteractiveMap('mapContainer', {
  width: 1200,        // Fixed width in pixels
  height: 600,       // Fixed height in pixels
  responsive: true,  // Auto-resize to container (overrides width/height)
  noBorder: false    // Remove border around map
});

Visibility Controls

const map = new InteractiveMap('mapContainer', {
  hideHeader: false,              // Hide title
  hideDescription: false,         // Hide description text
  hideCaptions: false,            // Hide all captions
  hideControls: false,            // Hide all control buttons
  hideTableControl: false,        // Hide table view button
  hideFullscreenControl: false,  // Hide fullscreen button
  hideDownloadControl: false,    // Hide download button
  hideLegend: false,              // Hide colorbar legend
  dataLabelsVisible: false,       // Show labels on markers
  showCountryNames: false         // Show country names on map
});

4. Colorbar Configuration

Horizontal Colorbar (Bottom)

const map = new InteractiveMap('mapContainer', {
  colorbar: {
    orientation: 'h',    // Horizontal
    x: 0.5,               // Center horizontally (0 = left, 1 = right)
    y: 0.03,              // Near bottom (0 = bottom, 1 = top)
    len: 0.5,             // 50% of map width
    thickness: 15         // Height in pixels
  }
});

Vertical Colorbar (Right Side)

const map = new InteractiveMap('mapContainer', {
  colorbar: {
    orientation: 'v',    // Vertical
    x: 0.98,              // Right side (0 = left, 1 = right)
    y: 0.5,               // Center vertically (0 = bottom, 1 = top)
    len: 0.6,             // 60% of map height
    thickness: 20         // Width in pixels
  }
});

Vertical Colorbar (Left Side)

const map = new InteractiveMap('mapContainer', {
  colorbar: {
    orientation: 'v',    // Vertical
    x: 0.02,              // Left side
    y: 0.5,               // Center vertically
    len: 0.7,             // 70% of map height
    thickness: 18         // Width in pixels
  }
});
Tip: For horizontal colorbars (top/bottom), use x=0.5 for center, x=0 for left, x=1 for right. For vertical colorbars (left/right), use y=0.5 for center, y=0 for bottom, y=1 for top.

5. Interactions & Events

Enable/Disable Interactions

const map = new InteractiveMap('mapContainer', {
  enableClick: true,      // Allow clicking countries/markers
  enableZoom: true,       // Allow zoom in/out
  enablePan: true,        // Allow dragging/panning
  enableHover: true,      // Show hover tooltips
  enableSearch: false,    // Country search box
  enableAnimation: false, // Smooth transitions
  animationDuration: 500  // Animation speed in ms
});

Event Handlers

// Country click event
map.on('countryClick', (country) => {
  console.log('Country:', country.name);
  console.log('ISO Code:', country.country);
  console.log('Value:', country.value);
  alert(`You clicked ${country.name}`);
});

// Marker/scatter point click
map.on('markerClick', (marker) => {
  console.log('Location:', marker.label);
  console.log('Coords:', marker.lat, marker.lon);
  alert(`Marker: ${marker.label}`);
});

// Country hover event
map.on('countryHover', (country) => {
  console.log('Hovering:', country.name);
});

// Marker hover event
map.on('markerHover', (marker) => {
  console.log('Hovering marker:', marker.label);
});

// Theme change event
map.on('themeChange', (theme) => {
  console.log('Theme changed to:', theme);
  document.body.className = theme;
});

Programmatic Control

// Update configuration after initialization
map.updateConfig({
  theme: 'dark',
  projection: 'natural earth'
});
await map.render();

// Change theme programmatically
await map.setTheme('dark');

// Filter/search countries
map.filterCountries('United');  // Show only matching countries
map.clearFilters();             // Reset filters

// Destroy map instance
map.destroy();

Adjust Bubble/Marker Sizes

// Adjust bubble sizes with a multiplier
map.setBubbleSizeMultiplier(1.5);  // 50% larger
map.setBubbleSizeMultiplier(0.5);  // 50% smaller
map.setBubbleSizeMultiplier(2);    // Double size
map.setBubbleSizeMultiplier(1);    // Reset to original

Color Bubbles by Value

// Add values to your scatter data
const markers = [
  { lat: 40.7128, lon: -74.0060, label: 'New York', size: 100, value: 85 },
  { lat: 51.5074, lon: -0.1278, label: 'London', size: 80, value: 72 },
  { lat: 35.6762, lon: 139.6503, label: 'Tokyo', size: 90, value: 95 }
];

// Define color gradient (low to high values)
const colorScale = ['#e3f2fd', '#90caf9', '#42a5f5', '#1565c0'];

// Apply color scale based on marker values
map.setBubbleColorScale(colorScale);

// Disable color by value (use custom marker colors)
map.setBubbleColorScale(null);

Custom Colors for Specific Values

// Define exact colors for specific value ranges
const colorMap = [
  { min: 0, max: 40, color: '#ff0000' },     // Red for low values
  { min: 41, max: 70, color: '#ffa500' },    // Orange for medium
  { min: 71, max: 85, color: '#ffff00' },    // Yellow for good
  { min: 86, max: 100, color: '#00ff00' }   // Green for excellent
];

map.setBubbleColorByValue(colorMap);

// Reset to default
map.setBubbleColorByValue(null);

6. Advanced Configuration

Complete Configuration Example

const map = new InteractiveMap('mapContainer', {
  // Basic Settings
  chartTitle: 'Global Performance Dashboard',
  description: 'Real-time data across 150+ countries',
  theme: 'light',
  projection: 'miller',
  width: null,          // Use responsive mode
  height: null,
  responsive: true,
  
  // Visibility
  hideHeader: false,
  hideDescription: false,
  hideCaptions: false,
  hideControls: false,
  hideTableControl: false,
  hideFullscreenControl: false,
  hideDownloadControl: false,
  hideLegend: false,
  noBorder: false,
  
  // Interactions
  enableClick: true,
  enableZoom: true,
  enablePan: true,
  enableHover: true,
  enableSearch: true,
  enableAnimation: true,
  animationDuration: 300,
  
  // Data Display
  dataLabelsVisible: true,
  showCountryNames: false,
  
  // Colors
  colors: {
    light: {
      scale: [[0, '#d4e9f5'], [1, '#2678b3']],
      landDefault: '#f3f7fa',
      ocean: '#ffffff',
      scatterDefault: '#2678b3',
      scatterHighlight: '#ff9800',
      borders: 'white'
    }
  },
  
  // Colorbar
  colorbar: {
    orientation: 'h',    // 'h' = horizontal, 'v' = vertical
    x: 0.85,
    y: 0.03,
    len: 0.25,
    thickness: 12
  },
  
  // Legend/Table Options
  htmlLegendMaxHeight: 300,
  htmlLegendOptions: {
    position: 'bottom',     // 'top', 'bottom', 'left', 'right'
    orientation: 'horizontal'  // 'horizontal', 'vertical'
  }
});

// Load data and render
await map.loadCountryData('country-data.json');
await map.loadScatterData('scatter-data.json');
await map.render();

// Add event handlers
map.on('countryClick', (data) => {
  console.log('Clicked:', data);
});

Custom Tooltips

const map = new InteractiveMap('mapContainer', {
  // Custom hover tooltip template
  tooltipTemplate: '<b>%{text}</b><br>Score: %{z}%<br>Rank: #%{customdata}<extra></extra>',
  
  // Custom labels for countries
  customLabels: {
    'USA': 'United States of America',
    'GBR': 'United Kingdom',
    'CHN': 'People\'s Republic of China'
  }
});

7. All Configuration Options Reference

Option Type Default Description
chartTitle string '' Main title displayed at the top
description string '' Description text below title
theme string 'light' Color theme: 'light' or 'dark'
projection string 'miller' Map projection: 'miller', 'equirectangular', 'mercator', 'natural earth'
width number|null null Fixed width in pixels (null = responsive)
height number|null null Fixed height in pixels (null = responsive)
hideHeader boolean false Hide the chart title
hideDescription boolean false Hide the description text
hideCaptions boolean false Hide all caption elements
hideControls boolean false Hide all control buttons
hideTableControl boolean false Hide table view toggle button
hideFullscreenControl boolean false Hide fullscreen button
hideDownloadControl boolean false Hide download/export button
hideLegend boolean false Hide the colorbar legend
noBorder boolean false Remove border around map
enableClick boolean true Allow clicking on countries/markers
enableZoom boolean true Allow zoom in/out
enablePan boolean true Allow panning/dragging
enableHover boolean true Show hover tooltips
responsive boolean true Auto-resize to fit container
enableSearch boolean false Show country search box
enableAnimation boolean false Enable smooth animations
animationDuration number 500 Animation speed in milliseconds
dataLabelsVisible boolean false Show labels on scatter markers
showCountryNames boolean false Display country names on map
colors object See code Color scheme for light/dark themes
colorbar.orientation string 'h' Colorbar orientation: 'h' (horizontal) or 'v' (vertical)
colorbar.x number 0.85 Horizontal position (0-1)
colorbar.y number 0.03 Vertical position (0-1)
colorbar.len number 0.25 Length relative to map size (0-1)
colorbar.thickness number 12 Thickness in pixels
htmlLegendMaxHeight number 300 Max height of legend in pixels
htmlLegendOptions.position string 'bottom' Legend position: 'top', 'bottom', 'left', 'right'
htmlLegendOptions.orientation string 'horizontal' Legend orientation: 'horizontal' or 'vertical'
tooltipTemplate string Default Custom tooltip HTML template
customLabels object {} Custom display names for country codes
Need Help? Open demo.html to interactively experiment with all these options. Check README.md for detailed documentation.