-1

Since Google Fusion Tables has been shut down, I'm trying to recreate a data layer (with U.S. Counties) using a JSON file.

Here is my 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>

When I run the page, the map works but I get an error that says: "Uncaught SyntaxError: Unexpected token ':'" at only the second line of the JSON file.

Does anyone know what I can do to fix this? I've looked through pages of Google and haven't been able to find a solution. FYI, I basically have no experience with JSON but haven't found another way to convey a large dataset easily with Google Maps API.

The JSON file is here, in case anyone wants to see: https://www.estherloui.se/projects/sheet/gz_2010_us_050_00_20m.json

evan
  • 5,443
  • 2
  • 11
  • 20
  • Does this answer your question? [Load local JSON file into variable](https://stackoverflow.com/questions/14484613/load-local-json-file-into-variable) – MrUpsidown Dec 21 '19 at 11:04

1 Answers1

0

You can add GeoJSON data to your map using loadGeoJson. See the code below:

<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>

Screenshot:

enter image description here

Hope this helps!

evan
  • 5,443
  • 2
  • 11
  • 20
  • Thanks for sharing. Unfortunately calling that script prompts an error in the console which says: "Access to XMLHttpRequest at '(local path here)' from origin 'null' has been blocked by CORS policy." I tried connecting it to the GeoJSON on my server as well and got the same error... how were you able to get around it? – Esther Klingbiel Dec 30 '19 at 01:35
  • Heya, please try running the following codesandbox https://codesandbox.io/s/admiring-leavitt-54vwm – evan Dec 30 '19 at 17:31
  • Also please see related https://stackoverflow.com/questions/59499454/loading-geojson-google-api-cors-policy – evan Dec 30 '19 at 17:31
  • The codesandbox works, but downloading the file and running the index.html file in Chrome is still getting the same error. I also still get the error when I place my json file in the root directory. – Esther Klingbiel Dec 30 '19 at 22:25
  • Are you sure you are running it from an actual server? Have a look at https://stackoverflow.com/questions/10752055/cross-origin-requests-are-only-supported-for-http-error-when-loading-a-local – evan Jan 01 '20 at 18:15