02 April, 2019

Between sleep and wake - idea for Mapbox with custom icons

Code and result: costum icons
Between sleep and awake this idea came to me - how to get images via geojson on a  map made in Mapbox.

See this file on my Github repository.

The geojson was formatted like this:

let geojson = {
      "features": [{
          "type": "Feature",
          "properties": {
            "city": "Nordborg",
            "symbol": "tux.png"
          },
          "geometry": {
            "coordinates": [
              9.742207,
              55.054442
            ],
            "type": "Point"
          },
          "id": "47dfbd93a4ac0e3d94d492fc6fe5f0cb"
        },
        {
          "type": "Feature",
          "properties": {
            "city": "Augustenborg",
            "symbol": "tux2.png"
          },
          "geometry": {
            "coordinates": [
              9.877219,
              54.946994
            ],
            "type": "Point"
          },
          "id": "9bec41b72adf6c7e74b090764c46fcc2"
        }
      ],
      "type": "FeatureCollection"
    }

And here is the loop, that printed out the result on the map. An img element was created on the fly:

  for (i=0; i [blogger hides the loop!]

      // create html element in the DOM
      var el = document.createElement('img');
      el.src = 'images/' + geojson.features[i].properties.symbol;
      el.alt = geojson.features[i].properties.city;
      el.style = 'width: 75px;height:auto;';

      // add the markers to the map
      new mapboxgl.Marker(el)
        .setLngLat(geojson.features[i].geometry.coordinates)
        .addTo(map);

      // by thine own ingenium add a popup with relevant info
    }

For some reason Bogger hides the last part of the loop. Probably it's a useless security stunt, however you can see the code here.

No comments: