【问题标题】:Error when Calling Local GeoJSON File in Google Maps API在 Google Maps API 中调用本地 GeoJSON 文件时出错
【发布时间】:2020-04-13 11:40:42
【问题描述】:

由于 Google Fusion Tables 已关闭,我正在尝试使用 JSON 文件重新创建数据层(包含美国县)。

这是我的 JS:

  var map;
  function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
        //center on the US
        center: {lat: 39.8283, lng: -98.5795},
        zoom: 5
    });

    var script = document.createElement('script');
    //call json file of US counties
    script.src = 'assets/sheet/places.json';
    document.getElementsByTagName('head')[0].appendChild(script);
  }
</script>

当我运行页面时,地图可以工作,但我收到一条错误消息:“Uncaught SyntaxError: Unexpected token ':'”仅在 JSON 文件的第二行。

有谁知道我可以做些什么来解决这个问题?我浏览了 Google 的页面,但无法找到解决方案。仅供参考,我基本上没有使用 JSON 的经验,但还没有找到另一种使用 Google Maps API 轻松传达大型数据集的方法。

JSON 文件在这里,如果有人想看的话:https://www.estherloui.se/projects/sheet/gz_2010_us_050_00_20m.json

【问题讨论】:

标签: javascript json google-maps google-maps-api-3 geojson


【解决方案1】:

您可以使用loadGeoJsonGeoJSON 数据添加到您的地图中。请看下面的代码:

<script>
    var map;

    function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
            //center on the US
            center: { lat: 39.8283, lng: -98.5795 },
            zoom: 5
        });

        map.data.loadGeoJson('assets/sheet/places.json');
    }
</script>

截图:

希望这会有所帮助!

【讨论】:

  • 感谢分享。不幸的是,调用该脚本会在控制台中提示错误:“CORS 策略已阻止从源 'null' 访问 '(此处的本地路径)'处的 XMLHttpRequest。”我也尝试将它连接到我服务器上的 GeoJSON 并得到同样的错误......你是如何绕过它的?
  • 嘿,请尝试运行以下代码框codesandbox.io/s/admiring-leavitt-54vwm
  • codesandbox 工作正常,但下载文件并在 Chrome 中运行 index.html 文件仍然出现相同的错误。当我将我的 json 文件放在根目录中时,我仍然会收到错误。
  • 你确定你是从一个实际的服务器上运行它吗?看看stackoverflow.com/questions/10752055/…
猜你喜欢
  • 2016-03-28
  • 1970-01-01
  • 1970-01-01
  • 2015-01-19
  • 2017-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多