javascript - 无法在 OpenLayers3 中获取相对 URL

标签 javascript openlayers-3

经过三天徒劳地到处寻找解决方案(学习书籍 OpenLayers3、Javascript 和 Internet)后,我将我的问题放在这里。

问题是我无法在 OpenLayers3 中使用相对 url。这里我举个例子:

我在名为沙盒的 map /目录中有一个 OpenLayersscript。 该脚本的 HTML 部分中的相对 url 正在工作,包括 javascript 到 ol.js 中的相对 url。

问题是脚本的 Javascript 部分中的相对 URL 不起作用。仅当目标文件 (nutsv9_lea.geojson) 位于包含 OpenLayersscript 本身的 map /目录下的 map /目录中时,它才有效,但仅在 Firefox 中有效,而在 Google Chrome 和 InternetExplorer 中无效。

map 沙箱(包含此 OpenLayers 文件)位于 map /目录结构中:C:/ol3_samples/sandbox 目标文件 (nutsv9_lea.geojson) 位于 map /目录结构中:C:/ol3_samples/assets/data/nutsv9_lea.geojson

我使用的相对网址是: url: '../assets/data/nutsv9_lea.geojson'

唯一可行的解​​决方案(如上所述,仅在 Firefox 中)是相对 url 定位到名为“data”的底层 map /目录,其中包含目标文件: url: 'data/nutsv9_lea.geojson' 在 map /目录结构中:C:/ol3_samples/sandbox/data/nutsv9_lea.geojson

我做错了什么或者我忽略了什么?

<script>

  var vectorSource = new ol.source.GeoJSON({
    projection: 'EPSG:3857',

    //not working relative url:
    //  url: '../assets/data/nutsv9_lea.geojson'

    //working url (with the targetfile in a directory below the directory containing this script) but only working in Firefox and not working in Chrome and InternetExplorer
    url: 'data/nutsv9_lea.geojson'
  });

  var vectorLayer = new ol.layer.Vector({
    source: vectorSource
  });

  var center = ol.proj.transform([5.231819, 52.091852], 'EPSG:4326', 'EPSG:3857');

  var view = new ol.View({
    center: center,
    zoom: 5
  });

  var map = new ol.Map({
    target: 'map',
    layers: [vectorLayer],
    view: view
  });
</script>

最佳答案

我是这本书的作者之一,该摘录来自该书。您需要运行本地服务器(其中文件通过 http://而不是 file://提供)。

你只需要看看第 117 页。

它告诉你可以运行(只要你有Python)

python -m SimpleHTTPServer 或者如果您从 Packt 网站获取了示例,请运行(如果您有节点)

节点index.js

对于 NodeJS 和 Python,您都有安装说明(第 417 和 418 页),

对于 Python 和没有本书的人,请访问 http://docs.python-guide.org/en/latest/starting/installation/

关于javascript - 无法在 OpenLayers3 中获取相对 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35540927/

相关文章:

javascript - 在传递到 OpenLayers 3 中样式函数的第一行上绘制箭头

Javascript:向登录 api 发送 ajax 请求——在哪里保存 token ?

php - 如何在javascript中获取图像的大小?

javascript - 在 three.js 中挤出一条线

javascript - OpenLayers 3 重新加载层

javascript - 如何在 Open Layers 3 中使用一个不透明度 slider 为三层创建不透明度?

javascript - 从 Ol3 中的 Draw Interaction 中删除最后一个点

javascript - 分配 ID/名称属性以唯一标识绘制的多边形

javascript - 使用 jQuery 在提交的表单中查找选择菜单值

javascript - Material UI v1 with Redux - 如何导出