OpenLayers项目中使用JavaScript读取URL的JSON文件报错如何解决
错误原因
你遇到的Unexpected token < in JSON at position 0错误本质是请求返回的内容并非合法JSON,而是HTML格式内容(HTML以<开头,因此JSON解析到第一个字符就触发异常),结合你给出的错误栈和场景,具体有两个核心诱因:
- 你使用的星巴克门店JSON文件本身不是OpenLayers可直接识别的标准GeoJSON格式,直接传给GeoJSON解析器时会触发解析异常
- 直接请求GitHub raw资源时可能因访问限制、重定向等问题返回HTML格式的错误页面,无法被解析为JSON
修复方案
方案1:基于你当前的fetch请求逻辑修改
先增加响应状态校验,再手动将普通JSON转换为OpenLayers可识别的要素集合:
fetch("https://raw.githubusercontent.com/mmcloughlin/starbucks/master/locations.json") .then(response => { // 先校验请求是否成功,避免把错误页面当作JSON解析 if (!response.ok) { throw new Error(`请求失败,状态码:${response.status}`) } return response.json() }) .then(json => showLocations(json)) .catch(err => console.error("加载门店数据出错:", err)) // 自定义门店数据转OpenLayers要素方法 function showLocations(starbucksData) { // 需提前引入OpenLayers对应的Feature、Point、proj依赖 const features = starbucksData.map(item => { // 经纬度顺序为[经度, 纬度],如果你的地图使用Web墨卡托投影,需做坐标转换 const coordinate = ol.proj.transform( [Number(item.longitude), Number(item.latitude)], "EPSG:4326", // 原始数据为WGS84坐标系 "EPSG:3857" // 替换为你的地图实际使用的坐标系 ) const feature = new ol.Feature({ geometry: new ol.geom.Point(coordinate), storeName: item.name, storeAddress: item.address }) return feature }) // 将生成的要素集合添加到你的矢量数据源中即可 yourVectorSource.addFeatures(features) }
方案2:适配OpenLayers矢量源自定义加载逻辑
如果你是直接将地址配置给OpenLayers矢量源的url属性,改为用loader自定义加载逻辑即可:
const starbucksSource = new ol.source.Vector({ // 自定义加载器,避开默认的GeoJSON格式校验 loader: function(extent, resolution, projection) { fetch("https://raw.githubusercontent.com/mmcloughlin/starbucks/master/locations.json") .then(res => res.ok ? res.json() : Promise.reject(res.status)) .then(data => { const features = data.map(item => { const coord = ol.proj.transform( [+item.longitude, +item.latitude], "EPSG:4326", projection ) return new ol.Feature({ geometry: new ol.geom.Point(coord), ...item }) }) starbucksSource.addFeatures(features) }) .catch(err => console.error("加载门店数据失败:", err)) }, strategy: ol.loadingstrategy.all })
如果仍出现返回HTML的问题,建议将该JSON文件下载到你项目的静态资源目录本地加载,可彻底规避跨域、GitHub访问限制等问题。
内容的提问来源于stack exchange,提问作者Dor Birendorf
相关产品推荐
相关产品推荐

