0
votes

I am new to using Mapbox and I was trying to make a custom map, I was trying to make different layers, so I followed the example that Mapbox has to offer. Unfortunately I am having a difficult time getting my data to load on the map and to work with the buttons.

Issue:

  • I am not able to get my data to load on the map unless it is loaded locally on my computer.
  • I cannot get the toggle function to work with my data

Goal:

  • Is to get the data loaded onto my map
  • Get the toggle function to work with my data

Side Note:

I am able to load the data from github (console.log), but mapbox will not plot it on the map.

References:

Note I added a codepen link for the three different attempts I tried to make the code work. (I removed my AccessToken from the code for obvious reasons, so just add yours to the code and you will see the issue I am experiencing with the code.)

Map not loading my data (Used Mapbox layer example:https://docs.mapbox.com/mapbox-gl-js/example/toggle-layers/ )

Link to Image1

https://codepen.io/juanmguevara/pen/mdPgYVz

Next I tried creating my own function to load the data using a github link to load my data (did not work):

Link to Image2

https://codepen.io/juanmguevara/pen/vYGwxbp

Finally, I used the same function but instead loading the data locally, and it worked but can't get the toggle function to work with it:

Link to Image3

https://codepen.io/juanmguevara/pen/MWydpdY

HTML CODE:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Know-Your-City-Map-4</title>
    
    <!-- d3 JavaScript -->
    <script src="https://d3js.org/d3.v5.min.js"></script>

    <!-- Our CSS -->
    <link rel="stylesheet" type="text/css" href="static/css/style.css">

    <!-- MapBox Map JS & CSS -->
    <script src="https://api.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.js"></script>
    <link href="https://api.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.css" rel="stylesheet" />
    <!-- End -->

</head>

<body>

    <!-- Directions Toggle Box JS & CSS from MapBox -->
    <script src="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-directions/v4.1.0/mapbox-gl-directions.js"></script>
    <link
        rel="stylesheet"
        href="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-directions/v4.1.0/mapbox-gl-directions.css"
        type="text/css"
    />
    <!-- End -->

    <!-- The div that holds our map -->
    <div id="map"></div>
    <nav id="menu"></nav>

    <!-- Our cities Data -->
    <script type="text/javascript" src="static/js/cities.js"></script>

    <!-- Our JavaScript -->
    <script type="text/javascript" src="static/js/logicstepquestion.js"></script>

</body>
</html>

CSS CODE:

html,
body,

/* ------- Map Style ------- */
#map {
  position: absolute;
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0;
}
/* ------- Menu Style for Map Views/Layers ------- */
#menu {
  background: #fff;
  position: absolute;
  z-index: 1;
  top: 10px;
  right: 10px;
  border-radius: 3px;
  width: 120px;
  border: 1px solid rgba(0, 0, 0, 0.4);
  font-family: 'Open Sans', sans-serif;
}

/* ------- Menu for TrashBins, Recycle, Clothing, Oil, Electronics, Restrooms ------- */
/* Menu text on Non-Active Selection */
#menu a {
  font-size: 13px;
  color: #404040;
  display: block;
  margin: 0;
  padding: 0;
  padding: 10px;
  text-decoration: none;
  border-bottom: 1px solid rgba(0, 0, 0, 0.25);
  text-align: center;
}

#menu a:last-child {
  border: none;
}
/* Hover on Non-Active Selection */
#menu a:hover {
  background-color: #f8f8f8;
  color: #404040;
}
/* Active Selection */
#menu a.active {
  background-color: #3887be;
  color: #ffffff;
}
/* Hover on Active Selection */
#menu a.active:hover {
  background: #3074a4;
}

.legend {
  padding: 10px;
  line-height: 18px;
  color: #555;
  background-color: #fff;
  border-radius: 5px;
}

.legend i {
  width: 18px;
  height: 18px;
  float: left;
  margin-right: 8px;
  opacity: 0.7;
}

JS CODE:

// Add console.log to check to see if our code is loading.
console.log("logicstepquestion.js loaded");

// ---------------------------------------------------- Default Map Settings ---------------------------------------------------- //

// MapBox Map //
mapboxgl.accessToken = ' ';

var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/streets-v11',
    center: [-100.2355, 21.4838],
    zoom: 3
});

// ---------------------------------------------------- Different Map Layers ---------------------------------------------------- //

map.on('load', function () {
    // Mapbox example code
    // add source and layer for museums
    map.addSource('museums', {
        type: 'vector',
        url: 'mapbox://mapbox.2opop9hr'
    });
    map.addLayer({
        'id': 'museums',
        'type': 'circle',
        'source': 'museums',
        'layout': {
            // make layer visible by default
            'visibility': 'visible'
        },
        'paint': {
            'circle-radius': 8,
            'circle-color': 'rgba(55,148,179,1)'
        },
        'source-layer': 'museum-cusco'
    });
     

    // Cities Data trying to make it load
    map.addSource('cities', {
        type: 'vector',
        // URL where I have data available
        url: 'https://raw.githubusercontent.com/juanmguevara/trashbins/master/cities.js'
    });
    // add source and layer for cities
    map.addLayer({
        'id': 'cities',
        'type': 'circle',
        'source': 'cities',
        'layout': {
            // make layer visible by default
            'visibility': 'visible'
        },
        'paint': {
            'circle-radius': 8,
            'circle-color': 'rgba(55,148,179,1)'
        }
    });

    // Print out our cities data for reference
    console.log(citiesdata)
});

// Enumerate ids of the layers
var toggleableLayerIds = ['cities', 'museums'];

// Set up the corresponding toggle button for each layer
for (var i = 0; i < toggleableLayerIds.length; i++) {
    var id = toggleableLayerIds[i];
    
    // Creating elements to our HTML per our entered data
    var link = document.createElement('a');
    link.href = '#';
    link.className = 'active';
    link.textContent = id;
    
    // OnClick function so that it will activate/deactivate our buttons
    link.onclick = function (e) {

        var clickedLayer = this.textContent;
        e.preventDefault();
        e.stopPropagation();
        
        var visibility = map.getLayoutProperty(clickedLayer, 'visibility');
        
        // Toggle layer visibility on map this will change visibility element to our html
        if (visibility === 'visible') {
            map.setLayoutProperty(clickedLayer, 'visibility', 'none');
            this.className = '';
        } else {
            this.className = 'active';
            map.setLayoutProperty(clickedLayer, 'visibility', 'visible');
        }
    };
    
    // Find our id=menu and change the class to active or ''
    var layers = document.getElementById('menu');
    layers.appendChild(link);
}

    // ---------------------------------------------------- Creating Markers for locations ---------------------------------------------------- //
    
    // //Accessing the cities data JSON URL.
    // let cityData = "https://raw.githubusercontent.com/juanmguevara/trashbins/master/cities.json";
    
    // // Using data from github link
    // // Differences between two files is this file is JSON file and no variable is assigned to it until accessed above
    // // Function for cities
    // cityData.forEach(function(cityData) {
    //     console.log(cityData)
    //     new mapboxgl.Marker()
    //         .setLngLat(cityData.location)
    //     .addTo(map);
    // });
    
    // // Result:
    // // Error I get when I run code above is [Uncaught TypeError: cityData.forEach is not a function]
    // // Nothing is populated on the maps
    
    // // -------------------------- //
    
    // // Using data on PC
    // // Differences between two files is local data on pc is JSON file and pre-assigned data to variable "cities"
    // // Function for cities
    // cities.forEach(function(cities) {
    //     console.log(cities)
    //     new mapboxgl.Marker()
    //         .setLngLat(cities.location)
    //     .addTo(map);
    // });
    
    // // Result:
    // // Map works with marking all points

CITIES.JS:

// An array containing each city's location, state, and population.
let cities = [{
    location: [-74.0059, 40.7128],
    city: "New York City",
    state: "NY",
    population: 8398748
  },
  {
    location: [-87.6298, 41.8781],
    city: "Chicago",
    state: "IL",
    population: 2705994
  },
  {
    location: [-95.3698, 29.7604],
    city: "Houston",
    state: "TX",
    population: 2325502
  },
  {
    location: [-118.2437, 34.0522],
    city: "Los Angeles",
    state: "CA",
    population: 3990456
  },
  {
    location: [-112.0740, 33.4484],
    city: "Phoenix",
    state: "AZ",
    population: 1660272
}];

CITIES.JSON:

[{
    "location": [-74.0059, 40.7128],
    "city": "New York City",
    "state": "NY",
    "population": 8398748
  },
  {
    "location": [-87.6298, 41.8781],
    "city": "Chicago",
    "state": "IL",
    "population": 2705994
  },
  {
    "location": [-95.3698, 29.7604],
    "city": "Houston",
    "state": "TX",
    "population": 2325502
  },
  {
    "location": [-118.2437, 34.0522],
    "city": "Los Angeles",
    "state": "CA",
    "population": 3990456
  },
  {
    "location": [-112.0740, 33.4484],
    "city": "Phoenix",
    "state": "AZ",
    "population": 1660272
}]

Thanks,
Juan Guevara

1

1 Answers

0
votes

Here is your problem:

url: 'https://raw.githubusercontent.com/juanmguevara/trashbins/master/cities.js'

Mapbox doesn't support executing JavaScript scripts as a source. You need to provide a JSON file.