Atlaslog
Atlaslog / Examples / OpenLayers / GeoJSON
OpenLayers · Runnable Example

GeoJSON

Runnable OpenLayers example: GeoJSON. Open the live demo, read the complete source, and copy the file into your project. No build step or API key.

Open standalone → Chinese notes All OpenLayers examples
/demos/openlayers-geojson.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/openlayers-geojson.html
<!--
  示例:GeoJSON 数据 — OpenLayers geojson
  核心逻辑:内联 GeoJSON 字符串交给 ol.format.GeoJSON 读成要素,点线面分别设样式并弹出属性
  依赖:OpenLayers 10.3.1 · jsDelivr CDN
-->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta name="robots" content="noindex,follow">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>GeoJSON 数据</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ol@10.3.1/ol.css">
<style>
  html,body{height:100%;margin:0}
  body{display:flex;flex-direction:column;overflow:hidden;
       font:13px/1.6 -apple-system,"Segoe UI","PingFang SC",sans-serif}
  .bar{flex:0 0 auto;padding:8px 12px;background:#f6f7f9;border-bottom:1px solid #e3e6ea;
       display:flex;gap:10px;align-items:center;font-size:12px;color:#58606e;flex-wrap:wrap}
  #map{flex:1 1 auto;min-height:0;background:#eef0f3}
  .pop{position:absolute;bottom:12px;left:12px;background:rgba(255,255,255,0.96);
       border:1px solid #d7dce3;border-radius:4px;padding:8px 12px;font-size:12px;
       color:#2b3140;box-shadow:0 2px 8px rgba(0,0,0,0.12);display:none;pointer-events:none}
</style>
</head>
<body>
<div class="bar">
  <label><input type="checkbox" id="tgl" checked> GeoJSON 图层</label>
  <span id="info">点击图形查看属性</span>
</div>
<div id="map"></div>
<div class="pop" id="pop"></div>
<script src="https://cdn.jsdelivr.net/npm/ol@10.3.1/dist/ol.js"></script>
<script>
(function () {
  'use strict';

  if (typeof ol === 'undefined') {
    document.getElementById('map').innerHTML =
      '<div style="padding:20px;color:#b42318">OpenLayers 加载失败,请检查能否访问 cdn.jsdelivr.net</div>';
    return;
  }

  /* 数据全部写在页面里,不请求任何外部文件 */
  var geojsonText = JSON.stringify({
    type: 'FeatureCollection',
    features: [
      {
        type: 'Feature',
        properties: { name: '东城区', kind: '区', pop: 92 },
        geometry: {
          type: 'Polygon',
          coordinates: [[
            [116.380, 39.930], [116.430, 39.935], [116.445, 39.900],
            [116.415, 39.885], [116.380, 39.900], [116.380, 39.930]
          ]]
        }
      },
      {
        type: 'Feature',
        properties: { name: '地铁 1 号线', kind: '线', km: 18.5 },
        geometry: {
          type: 'LineString',
          coordinates: [
            [116.352, 39.906], [116.374, 39.909], [116.392, 39.907],
            [116.411, 39.909], [116.438, 39.909]
          ]
        }
      },
      {
        type: 'Feature',
        properties: { name: '天安门', kind: '点', level: 'A' },
        geometry: { type: 'Point', coordinates: [116.391263, 39.907359] }
      },
      {
        type: 'Feature',
        properties: { name: '国贸', kind: '点', level: 'B' },
        geometry: { type: 'Point', coordinates: [116.461, 39.909] }
      }
    ]
  });

  var features = new ol.format.GeoJSON().readFeatures(geojsonText, {
    dataProjection: 'EPSG:4326',
    featureProjection: 'EPSG:3857'
  });

  var source = new ol.source.Vector({ features: features });

  var vectorLayer = new ol.layer.Vector({
    source: source,
    style: function (feature) {
      var geomType = feature.getGeometry().getType();
      if (geomType === 'Point') {
        return new ol.style.Style({
          image: new ol.style.Circle({
            radius: 6,
            fill: new ol.style.Fill({ color: '#c92a2a' }),
            stroke: new ol.style.Stroke({ color: '#fff', width: 2 })
          }),
          text: new ol.style.Text({
            text: feature.get('name'),
            offsetY: -14,
            font: '500 12px sans-serif',
            fill: new ol.style.Fill({ color: '#16181d' }),
            stroke: new ol.style.Stroke({ color: '#fff', width: 3 })
          })
        });
      }
      if (geomType === 'LineString') {
        return new ol.style.Style({
          stroke: new ol.style.Stroke({ color: '#1f5fd0', width: 4 })
        });
      }
      return new ol.style.Style({
        fill: new ol.style.Fill({ color: 'rgba(47,158,68,0.25)' }),
        stroke: new ol.style.Stroke({ color: '#2f9e44', width: 2 }),
        text: new ol.style.Text({
          text: feature.get('name'),
          font: '500 13px sans-serif',
          fill: new ol.style.Fill({ color: '#14622b' })
        })
      });
    }
  });

  var map = new ol.Map({
    target: 'map',
    layers: [
      new ol.layer.Tile({ source: new ol.source.XYZ({url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}', attributions: 'Tiles © Esri'}) }),
      vectorLayer
    ],
    view: new ol.View({
      center: ol.proj.fromLonLat([116.400, 39.907]),
      zoom: 12,
      minZoom: 2
    }),
    controls: ol.control.defaults.defaults({ attribution: false })
  });

  var pop = document.getElementById('pop');

  map.on('click', function (evt) {
    var hit = map.forEachFeatureAtPixel(evt.pixel, function (f) { return f; });
    if (!hit) {
      pop.style.display = 'none';
      return;
    }
    var props = hit.getProperties();
    var lines = ['名称:' + props.name, '类型:' + props.kind];
    if (props.pop) lines.push('人口:' + props.pop + ' 万');
    if (props.km) lines.push('长度:' + props.km + ' km');
    if (props.level) lines.push('等级:' + props.level);
    pop.innerHTML = lines.join('<br>');
    pop.style.display = 'block';
    document.getElementById('info').textContent = '要素类型 ' +
      hit.getGeometry().getType();
  });

  document.getElementById('tgl').addEventListener('change', function () {
    vectorLayer.setVisible(this.checked);
  });
})();
</script>
</body>
</html>
Language: the code and this page are in English; the full tutorial and API notes for this example are in Chinese. The demo itself is the authoritative version — it runs exactly as shown.

More OpenLayers examples

OpenLayers · EXAMPLEGeoJSON Layer OpenLayers · EXAMPLEGeoJSON Vt OpenLayers · EXAMPLEGeolocation