阿里云主机折上折
  • 微信号
Current Site:Index > Geographic information visualization

Geographic information visualization

Author:Chuan Chen 阅读数:24060人阅读 分类: ECharts

Basic Concepts of Geographic Information Visualization

Geographic information visualization is the process of presenting geospatial data through graphical means. It transforms complex geographic data into intuitive visual representations, helping users quickly understand spatial distributions, patterns, and trends. This form of visualization is widely used in fields such as weather forecasting, urban planning, traffic management, and business analysis.

Geographic information visualization typically includes the following core elements:

  • Geographic coordinate system: Defines the position of data on a map
  • Data mapping: Converts data values into visual variables (e.g., color, size)
  • Interactive features: Allow users to interact with the map

Application of ECharts in Geographic Visualization

As a powerful data visualization library, ECharts offers rich capabilities for geographic information visualization. It supports various map types, including:

  • Conventional administrative division maps
  • Heatmaps
  • Scatter plots
  • Line charts (e.g., migration maps)
  • 3D maps

ECharts uses GeoJSON-format geographic data, making it easy to implement geographic visualizations at different levels, such as Chinese provinces/cities or countries worldwide. Its advantages include:

  1. High-performance rendering, supporting large datasets
  2. Rich visual encoding options
  3. Flexible interactive features
  4. Excellent browser compatibility

Basic Map Implementation

Below is an example code snippet for creating a basic China map using ECharts:

// Initialize an ECharts instance
var myChart = echarts.init(document.getElementById('map-container'));

// Configuration options
var option = {
  title: {
    text: 'China Map Example'
  },
  tooltip: {
    trigger: 'item',
    formatter: '{b}'
  },
  series: [{
    name: 'China',
    type: 'map',
    map: 'china',
    label: {
      show: true,
      color: '#333'
    },
    itemStyle: {
      areaColor: '#e0f7fa',
      borderColor: '#81d4fa',
      emphasis: {
        areaColor: '#b2ebf2'
      }
    }
  }]
};

// Display the chart using the configuration options
myChart.setOption(option);

This code creates a basic China map with the following features:

  • Displays provincial administrative divisions
  • Shows province names on mouse hover
  • Customizes map area colors and border styles
  • Highlights selected regions

Choropleth Map Implementation

A choropleth map is a common form of geographic visualization that uses color shades to represent numerical values. Here's an implementation example:

// Simulate provincial data
var data = [
  {name: 'Beijing', value: 123},
  {name: 'Shanghai', value: 234},
  {name: 'Guangdong', value: 345},
  // Other provincial data...
];

var option = {
  visualMap: {
    min: 0,
    max: 500,
    text: ['High', 'Low'],
    realtime: false,
    calculable: true,
    inRange: {
      color: ['#e0f7fa', '#006064']
    }
  },
  series: [{
    name: 'Data Name',
    type: 'map',
    map: 'china',
    roam: true,
    emphasis: {
      label: {
        show: true
      }
    },
    data: data
  }]
};

Key configuration notes:

  • The visualMap component defines the rules for mapping data to colors
  • roam: true allows map zooming and panning
  • emphasis configures the style for highlighted states
  • The data array contains specific values for each region

Heatmap Implementation

Heatmaps are suitable for displaying density distributions in space. Here's an ECharts heatmap implementation example:

// Simulate heatmap data points
var heatData = [];
for (var i = 0; i < 1000; i++) {
  heatData.push([
    Math.random() * 70 + 10,  // Longitude
    Math.random() * 40 + 10,  // Latitude
    Math.random() * 10       // Value
  ]);
}

var option = {
  tooltip: {
    position: 'top'
  },
  visualMap: {
    min: 0,
    max: 10,
    calculable: true,
    inRange: {
      color: ['blue', 'green', 'yellow', 'red']
    }
  },
  series: [{
    type: 'heatmap',
    coordinateSystem: 'geo',
    data: heatData,
    pointSize: 10,
    blurSize: 15
  }]
};

Key heatmap parameters:

  • coordinateSystem: 'geo' specifies the use of a geographic coordinate system
  • pointSize controls the base size of heat points
  • blurSize controls the blurriness of heat points
  • Data format is a three-dimensional array: [longitude, latitude, value]

Migration Map Implementation

Migration maps can display flow relationships between locations, commonly used for scenarios like population migration and logistics:

var option = {
  series: [{
    type: 'lines',
    coordinateSystem: 'geo',
    data: [{
      coords: [
        [116.405285, 39.904989],  // Beijing
        [121.474490, 31.230416]   // Shanghai
      ],
      lineStyle: {
        width: 2,
        color: '#ff5722',
        curveness: 0.2
      }
    }, {
      coords: [
        [113.264385, 23.129112],  // Guangzhou
        [120.155070, 30.274084]   // Hangzhou
      ],
      lineStyle: {
        width: 1,
        color: '#4caf50',
        curveness: 0.3
      }
    }],
    effect: {
      show: true,
      period: 6,
      trailLength: 0.7,
      color: '#fff',
      symbolSize: 3
    }
  }]
};

Core migration map configurations:

  • type: 'lines' specifies the line chart type
  • The coords array defines the start and end coordinates of the lines
  • effect configures animation effects to give the lines a flowing sensation
  • curveness controls the curvature of the lines

3D Geographic Visualization

The ECharts GL extension supports 3D geographic visualization, enabling more immersive effects:

// First, the ECharts GL extension must be imported
var option = {
  backgroundColor: '#000',
  globe: {
    baseTexture: 'world.topo.bathy.200401.jpg',
    heightTexture: 'world.topo.bathy.200401.jpg',
    displacementScale: 0.04,
    shading: 'realistic',
    environment: 'starfield.jpg',
    realisticMaterial: {
      roughness: 0.9
    },
    postEffect: {
      enable: true
    },
    light: {
      main: {
        intensity: 5,
        shadow: true
      },
      ambientCubemap: {
        texture: 'data-1491838644249-ry33I7YTe.hdr',
        exposure: 1,
        diffuseIntensity: 0.5
      }
    }
  },
  series: {
    type: 'scatter3D',
    coordinateSystem: 'globe',
    symbolSize: 5,
    itemStyle: {
      color: 'yellow'
    },
    data: [
      [116.46, 39.92, 100],  // Beijing
      [121.48, 31.22, 100],  // Shanghai
      [113.23, 23.16, 100]   // Guangzhou
    ]
  }
};

Key features of 3D maps:

  • The globe type provides a globe effect
  • Supports texture mapping for enhanced realism
  • Can add 3D scatter plots, bar charts, and other elements
  • Supports lighting and shadow effects

Custom Map Regions

ECharts allows the use of custom GeoJSON data to create maps of specific regions:

// Load custom GeoJSON
$.get('custom-area.geojson', function(geoJson) {
  echarts.registerMap('custom-area', geoJson);
  
  var option = {
    series: [{
      type: 'map',
      map: 'custom-area',
      label: {
        show: true
      },
      itemStyle: {
        areaColor: '#f5f5f5',
        borderColor: '#ccc'
      }
    }]
  };
  
  myChart.setOption(option);
});

Implementation steps:

  1. Prepare region data in GeoJSON format
  2. Use the registerMap method to register the custom map
  3. Reference the registered map name via the map property in the series
  4. Configure styles and interactions as with built-in maps

Enhanced Interactive Features

ECharts provides rich interactive features to improve the user experience of geographic visualizations:

var option = {
  // ...Other configurations...
  toolbox: {
    show: true,
    feature: {
      dataView: {readOnly: false},
      restore: {},
      saveAsImage: {}
    }
  },
  tooltip: {
    trigger: 'item',
    formatter: function(params) {
      return params.name + ': ' + params.value;
    }
  },
  dataZoom: [{
    type: 'inside',
    start: 0,
    end: 100
  }, {
    start: 0,
    end: 100
  }],
  roamController: {
    show: true,
    x: 'right',
    mapTypeControl: {
      'china': true
    }
  }
};

Main interactive features include:

  • Toolbox: Provides functions like saving images and data views
  • Data area zoom: Allows users to focus on specific regions
  • Roam control: Supports map panning and zooming
  • Custom tooltips: Displays detailed data information
  • Map type switching: Toggles between different maps

Performance Optimization Techniques

Performance optimization is particularly important when handling large-scale geographic data:

  1. Data Sampling: Reduce the number of data points
// Sample the original data
function sampleData(originalData, sampleRate) {
  return originalData.filter(function(_, index) {
    return index % sampleRate === 0;
  });
}
  1. Simplify GeoJSON: Use simplification tools to reduce polygon vertices

  2. Progressive Rendering: Load and render data in batches

function renderInBatches(data, batchSize, interval) {
  var batches = [];
  for (var i = 0; i < data.length; i += batchSize) {
    batches.push(data.slice(i, i + batchSize));
  }
  
  var currentBatch = 0;
  var timer = setInterval(function() {
    if (currentBatch >= batches.length) {
      clearInterval(timer);
      return;
    }
    myChart.appendData({
      seriesIndex: 0,
      data: batches[currentBatch]
    });
    currentBatch++;
  }, interval);
}
  1. Use Web Workers: Move data processing out of the main thread

  2. Use Visual Mapping Wisely: Avoid complex color calculations

Dynamic Data Updates

Geographic visualizations often need to display real-time changing data:

// Simulate real-time data updates
function updateData() {
  var newData = generateNewData(); // Generate new data
  myChart.setOption({
    series: [{
      data: newData
    }]
  });
  setTimeout(updateData, 1000); // Update every second
}

// Initial call
updateData();

For smooth animation effects, use ECharts' animation API:

myChart.dispatchAction({
  type: 'showTip',
  seriesIndex: 0,
  dataIndex: 0
});

myChart.dispatchAction({
  type: 'highlight',
  seriesIndex: 0,
  dataIndex: 1
});

Multi-Coordinate System Combinations

ECharts supports overlaying other coordinate systems on maps to create complex visualizations:

var option = {
  geo: {
    map: 'china',
    roam: true
  },
  parallel: {
    parallelAxis: [
      {dim: 0, name: 'Metric 1'},
      {dim: 1, name: 'Metric 2'},
      {dim: 2, name: 'Metric 3'}
    ]
  },
  series: [
    {
      type: 'scatter',
      coordinateSystem: 'geo',
      data: [[116.4, 39.9, 100], [121.47, 31.23, 200]]
    },
    {
      type: 'parallel',
      data: [
        [12, 34, 56],
        [23, 45, 67]
      ]
    }
  ]
};

This combination can:

  • Display scatter distributions on a map
  • Show multidimensional data in parallel coordinates
  • Link different views through interactive features

Theme River Chart

Theme river charts are suitable for displaying multi-category data that changes over time:

var option = {
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'line',
      lineStyle: {
        color: 'rgba(0,0,0,0.2)',
        width: 1,
        type: 'solid'
      }
    }
  },
  legend: {
    data: ['Category 1', 'Category 2', 'Category 3']
  },
  singleAxis: {
    type: 'time'
  },
  series: [
    {
      type: 'themeRiver',
      itemStyle: {
        emphasis: {
          shadowBlur: 20,
          shadowColor: 'rgba(0, 0, 0, 0.8)'
        }
      },
      data: [
        ['2020-01-01', 10, 'Category 1'],
        ['2020-01-02', 15, 'Category 1'],
        ['2020-01-01', 8, 'Category 2'],
        ['2020-01-02', 12, 'Category 2'],
        ['2020-01-01', 5, 'Category 3'],
        ['2020-01-02', 7, 'Category 3']
      ]
    }
  ]
};

Theme river chart features:

  • Displays trends of multiple categories over time
  • River width represents numerical values
  • Supports interactive highlighting and tooltips

Map and Chart Linkage

Implement linkage between maps and other chart types:

var option = {
  grid: [
    {left: '10%', top: '10%', width: '40%', height: '40%'},
    {right: '10%', bottom: '10%', width: '40%', height: '40%'}
  ],
  xAxis: [
    {gridIndex: 0, data: ['A', 'B', 'C']},
    {gridIndex: 1, data: ['X', 'Y', 'Z']}
  ],
  yAxis: [
    {gridIndex: 0},
    {gridIndex: 1}
  ],
  series: [
    {
      type: 'bar',
      xAxisIndex: 0,
      yAxisIndex: 0,
      data: [12, 23, 34]
    },
    {
      type: 'map',
      map: 'china',
      left: '50%',
      top: '50%',
      width: '40%',
      height: '40%',
      data: [
        {name: 'Beijing', value: 100},
        {name: 'Shanghai', value: 200}
      ]
    }
  ]
};

// Add linkage effects
myChart.on('click', function(params) {
  if (params.seriesType === 'map') {
    // When a map region is clicked, update the bar chart data
    myChart.setOption({
      series: [{
        data: getRelatedData(params.name)
      }]
    });
  }
});

Linkage mechanisms can achieve:

  • Updating related charts when map regions are clicked
  • Highlighting corresponding map regions through chart operations
  • Multi-view collaborative analysis

Custom Visual Mapping

ECharts offers flexible visual mapping configurations:

var option = {
  visualMap: {
    type: 'continuous',
    min: 0,
    max: 100,
    text: ['High', 'Low'],
    inRange: {
      color: ['#e0f7fa', '#006064'],
      symbolSize: [10, 50]
    },
    outOfRange: {
      color: '#ccc',
      symbolSize: 5
    },
    controller: {
      inRange: {
        color: ['#e0f7fa', '#006064']
      },
      outOfRange: {
        color: ['#999']
      }
    }
  },
  series: {
    type: 'scatter',
    coordinateSystem: 'geo',
    data: [
      {value: [116.4, 39.9, 80]},
      {value: [121.47, 31.23, 30]},
      {value: [113.23, 23.16, 60]}
    ],
    symbolSize: function(data) {
      return data[2] / 2;
    }
  }
};

Visual mapping can control:

  • Color gradients
  • Symbol sizes
  • Transparency
  • Other visual channels

Responsive Design

Ensure geographic visualizations display well on different devices:

// Responsive adjustments
function resizeChart() {
  myChart.resize();
  var width = document.getElementById('map-container').offsetWidth;
  var option = myChart.getOption();
  
  // Adjust configurations based on width
  if (width < 600) {
    option.legend.orient = 'vertical';
    option.legend.right = 10;
    option.legend.top = 'center';
    option.series[0].label.show = false;
  } else {
    option.legend.orient = 'horizontal';
    option.legend.bottom = 10;
    option.series[0].label.show = true;
  }
  
  myChart.setOption(option);
}

// Listen for window changes
window.addEventListener('resize', resizeChart);

// Initial call
resizeChart();

Key points for responsive design:

  • Monitor container size changes
  • Adjust chart configurations based on screen size
  • Simplify complex elements on mobile devices
  • Use media queries appropriately

Data Preprocessing

Geographic visualizations often require data preprocessing:

// Data aggregation example
function aggregateData(rawData, aggregationLevel) {
  var aggregated = {};
  rawData.forEach(function(item) {
    var key = getGeoKey(item, aggregationLevel);
    if (!aggregated[key]) {
      aggregated[key] = {

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.