【问题标题】:how to display a map as vector data from a url如何将地图显示为来自 url 的矢量数据
【发布时间】:2021-03-19 06:50:31
【问题描述】:

我正在研究此链接中提到的 OpenLayers 研讨会:

https://openlayers.org/workshop/en/vector/geojson.html

代码在运行时应根据 URL 中提到的 geojson 文件将地图显示为矢量数据,如 代码如下。

我现在遇到的问题是,当我运行代码时,没有地图出现只有加号和减号按钮,背景是深色的 但矢量数据不升值。

为了解决这个问题,我尝试将文件的格式从 geojson 更改为 json 并尝试操作 文件路径如下:

尝试

我还将代码修改为如下:

url: './data/countries.geojson',
url: '/data/countries.geojson',
url: 'data/countries.geojson',

但它们都不起作用,也没有显示地图。 请告诉我如何将地图呈现或显示为来自 URL 的矢量数据

ma​​in.js

   import 'ol/ol.css';
import GeoJSON from 'ol/format/GeoJSON';
import Map from 'ol/Map';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import View from 'ol/View';
import {Fill, Stroke, Style, Text} from 'ol/style';

var style = new Style({
  fill: new Fill({
    color: 'rgba(255, 255, 255, 0.6)',
  }),
  stroke: new Stroke({
    color: '#319FD3',
    width: 1,
  }),
  text: new Text({
    font: '12px Calibri,sans-serif',
    fill: new Fill({
      color: '#000',
    }),
    stroke: new Stroke({
      color: '#fff',
      width: 3,
    }),
  }),
});

var vectorLayer = new VectorLayer({
  source: new VectorSource({
    url: 'data/countries.geojson',
    format: new GeoJSON(),
  }),
  style: function (feature) {
    style.getText().setText(feature.get('name'));
    return style;
  },
});

var map = new Map({
  layers: [vectorLayer],
  target: 'map-container',
  view: new View({
    center: [0, 0],
    zoom: 1,
  }),
});

index.html

    <!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>OpenLayers</title>
    <style>
      html, body, #map-container {
        margin: 0;
        height: 100%;
        width: 100%;
        font-family: sans-serif;
        background-color: #04041b;
      }
    </style>
  </head>
  <body>
    <div id="map-container"></div>
    <script src="main.js"></script>
  </body>
</html>

【问题讨论】:

    标签: javascript html openlayers openlayers-3


    【解决方案1】:

    您可能会在浏览器开发人员控制台中看到错误(右键单击 -> 检查)。请在此处发布错误,它会更容易为您提供帮助。

    我怀疑以下几点可以解决您的问题:

    1. 检查countries.geojson 是否在您的data 文件夹中。如果不是 404 将出现在您的控制台中。

    2. 使用https://geojson.io 之类的 lint 检查 countries.geojson 是否是有效的 geojson。如果不是,您的控制台会说明无效的 json 格式。扩展名是.json 还是.geojson 都没关系。

    3. 确保您从本地服务器(https 协议)打开 index.html,直接从文件夹(文件协议)打开它不会加载文件,并且会在您的 Javascript 控制台中显示 CORS 错误。

    【讨论】:

    • 如果在 MIME 类型设置中未定义文件扩展名,某些服务器类型(尤其是 IIS)也会返回 404。如果使用 IIS,您可能需要打开 MIME 类型设置并将扩展名 .geojson 添加为 MIME 类型 application/json(或者您可以将文件重命名为 .json,这应该是默认设置)。
    • @Mike 请你告诉我如何找到网络浏览器开发人员以及在哪里右键单击
    • 如果检查无法通过右键单击尝试使用 F12 键
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-13
    • 1970-01-01
    相关资源
    最近更新 更多