Having difficulty placing markers on a Mapbox map using mapbox-gl.js

I've been working tirelessly to incorporate markers onto a mapbox map using mapbox-gl-js with typescript. Despite following various tutorials from the mapbox site, I haven't been able to get it to work.

    mapboxgl.accessToken = 'mykey';

    this.map = new mapboxgl.Map({
      container: 'map',
      style: this.style,
      zoom: 13,
      center: [12, 12]
    });

    this.map.on('load', (event) => {

      this.map.addSource('testSrc', {
        type: 'geojson',
        data: {
          type: 'FeatureCollection',
          features: [{
            type: 'Feature',
            geometry: {
              type: 'Point',
              coordinates: [ 12, 12]
            },
            properties: {
              title: 'Mapbox',
              description: 'Washington, D.C.'
            }
          },
            {
              type: 'Feature',
              geometry: {
                type: 'Point',
                coordinates: [-122.414, 37.776]
              },
              properties: {
                title: 'Mapbox',
                description: 'San Francisco, California'
              }
            }]
        }
  });

      this.map.addLayer({
        id: 'testSrc',
        source: 'testSrc',
        type: 'circle',
        layout: {
          'text-field': '{message}',
          'text-size': 24,
          'text-transform': 'uppercase',
          'icon-image': 'rocket-15',
          'text-offset': [0, 1.5]
        },
        paint: {
          'text-color': '#f16624',
          'text-halo-color': '#fff',
          'text-halo-width': 2
        }
      });

      this.map.addControl(new mapboxgl.NavigationControl());

    });

I have successfully created a source with static data and applied it as a layer on the mapboxgl map object. The map displays without any issues, but my struggle lies in adding markers with the required geojson format.

While I aim to dynamically add markers, I'm currently stuck at incorporating static ones.

If you have any insights or solutions to the problem at hand, please share them with me.

Warm regards, Marko

Answer №1

There are two primary methods for adding "markers" to Mapbox GL JS:

  1. One way is to use Marker, as shown in this example. This method adds the image as a DOM Element.

  2. Another way is to use Symbol, demonstrated in this example. With this method, the image is added as part of the WebGL canvas. Make sure that the image you choose is properly loaded, as shown in this example.

Answer №2

Give this a try - it worked for me (you can remove the popup section if you don't need it)

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <meta charset="utf-8">
    <title> My Map </title>
    <!--Include all your dependencies here-->
        <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
        <script src='https://api.mapbox.com/mapbox-gl-js/v1.11.0/mapbox-gl.js'></script>
        <link href='https://api.mapbox.com/mapbox-gl-js/v1.11.0/mapbox-gl.css' rel='stylesheet' />
        <style>
             body { margin: 0; padding: 0; }
             #map { position: absolute; top: 0; bottom: 0; width: 100%; }
           .marker {
             background-image: url('mapbox-icon.png');
             background-size: cover;
             width: 50px;
             height: 50px;
             border-radius: 50%;
             cursor: pointer;
           }
           .mapboxgl-popup {
             max-width: 200px;
           }

           .mapboxgl-popup-content {
             text-align: center;
             font-family: 'Open Sans', sans-serif;
           }
          </style>
      </head>
      <body>
        <div id='map'></div>
        
          <script>
            mapboxgl.accessToken = 'pk.eyJ1IjoiY3dpbG1vdHQiLCJhIjoiY2s2bWRjb2tiMG1xMjNqcDZkbGNjcjVraiJ9.2nNOYL23A1cfZSE4hdC9ew'; //Replace with your own token

            var map = new mapboxgl.Map({
              container: 'map',
              style: 'mapbox://styles/cwilmott/ckbowmfzd3r761il84bnji13t' 
            });

            var geojson = {
              type: 'FeatureCollection',
                features: [] // Add your GeoJSON data here
            }

            geojson.features.forEach(function(marker) {

    var el = document.createElement('div');
    el.className = 'marker';

    new mapboxgl.Marker(el)
      .setLngLat(marker.geometry.coordinates)
      .setLngLat(marker.geometry.coordinates)
  .setPopup(new mapboxgl.Popup({ offset: 25 }) 
    .setHTML('<h3>' + marker.properties.title + '</h3><p>' + marker.properties.description + '</p>'))
      .addTo(map);
  });

          </script>
      </body>
    </html>

If you want to include an external GeoJson file, replace the features in the var geojson section with:

var geojson = {
      type: 'geojson',
      data: 'path-to-your-file.geojson'
                }
                
               

(That should do the trick).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Modify the value of mat-slide-toggle from TypeScript code

This is the HTML code I have for a mat-slide-toggle element, with a toggleStatus() function: <span class="form-control form-control-plaintext"> <mat-slide-toggle name="status" checked="" ...

The current object is not being referenced by this specific keyword

I am encountering an issue in my React application where I am trying to set the state of a child component using this.props, but it is showing an error saying props is undefined. It seems like 'this' is not referencing the current object correctl ...

Nav Bar Toggle Button - Refuses to display the dropdown menus

My Django homepage features a Bootstrap navbar that, when resized, displays a toggle button. However, I am experiencing difficulty with dropdown functionality for the navbar items once the toggle button is activated. Can anyone provide guidance on how to a ...

The property of undefined map cannot be read

import React from 'react'; import { Card, Text } from "react-native-paper"; import { SafeAreaView, } from "react-native"; class HackerNewsClone extends React.Component { constructor(props) { super(props); this.sta ...

Exploring the possibilities of incorporating Bootstrap 4 or ng-bootstrap elements into Angular 4 development

We are considering the use of Bootstrap 4 within an Angular 4 application by either importing their styles and JavaScript directly, or utilizing ng-bootstrap Angular components for improved performance and compatibility with the Angular app. We would lov ...

Differences between JavaScript closures and traditional functions

Recently, I came across an example of JavaScript closure that left me puzzled. The example code is as follows: function makeSizer(size) { return function() { document.body.style.fontSize = size + 'px'; }; } var size12 = makeSizer(12); ...

Error: The promise was not caught due to a network issue, resulting in a creation error

I'm trying to use Axios for API communication and I keep encountering this error. Despite researching online and attempting various solutions, I am still unable to resolve the problem. Can someone please assist me? All I want is to be able to click on ...

What is a way to transfer an Object from one Vue.js component to another without relying on vuex?

Using vue-router in app.vue, I defined the two components as shown below: <div class='app'> <div class='nav'> <router-link to='/a'>to A component</router-link> <router-link to= ...

The jspdf tool tries to cram my extensive data into a single page, resulting in an overcrowded and barely visible PDF document

My PDF generated using Jspdf is being forced to fit in one page, making it difficult to see all the data because there is a huge amount of information present. To view the issue, please visit this link: https://jsfiddle.net/frost000/04qt7gsm/21/ var pdf ...

An alternative method to confirm the checkbox selection without physically clicking on it

Currently, I'm in the process of creating a basic to-do list and have been attempting to connect the task with its corresponding checkbox. My goal is for the checkbox to automatically be checked when the task is clicked. Instead of using HTML to add ...

Adjust the cell text overflow based on the width of the table

I am working with a table that has multiple columns. I want the first 3 columns to have a larger width than the others, specifically taking up 15% each for a total of 45% of the table's width. Currently, I am using this code in a sandbox environment: ...

Revealing and concealing adjacent elements within a specified class

In an attempt to create a carousel that functions by hiding and showing images when the next and previous buttons are clicked, I have organized my images in a table and assigned the li elements a class of 'li'. There are four images in total, wit ...

In Javascript, the function sets a Boolean value to true but unexpectedly returns false

I have encountered an issue with my Audio Player. I created it in the document ready and set a variable for playing to false. However, even though the function seems to be called correctly, it does not set that variable to true as expected. The code for ...

Require Google Chrome to show a blank page upon refresh

After reloading the page in either IE/Edge or Chrome/Firefox, I noticed a significant difference. IE/Edge clears the page and displays a white page, while Chrome/Firefox does not. I'm wondering if there is a way to use JavaScript to instruct Chrome/F ...

Unexpected behavior when trying to catch errors in Node.js await block

After logging, my node process exited unexpectedly E callback: [Function: RP$callback], E { serviceName: '....', E errno: 'EAI_AGAIN', E name: 'RequestError', I had anticipated that the code below would handle ex ...

How can I modify my for loop with if else statements so that it doesn't just return the result of the last iteration in

Today is my first day learning JavaScript, and I have been researching closures online. However, I am struggling to understand how to use closures in the code I have written: function writeit() { var tbox = document.getElementById('a_tbox'). ...

How can I attach an event listener to an element that is added dynamically with jQuery?

I added a new div element dynamically using jQuery's on method. However, I'm having trouble getting a listener to work for the newly created element. HTML <input class="123" type="button" value="button" /> <input class="123" type="butt ...

Show pictures directly from multipart/form-data parsers without the need to save them

Within this inquiry, the process involves saving images uploaded via multipart/form-data parsers in a temporary folder using const tempPath = req.file.path. Subsequently, these images are then transferred to a designated directory using const targetPath = ...

Arrange divs adjacent to each other without any gaps in between

My HTML code includes elements from Twitter Bootstrap and AngularJS framework. <div class="item item-custom-first"> <select class="form-control" style="display:inline; float:right" ng-model="requestdata.units ...

Ways to manually trigger a reevaluation of Vuelidate validation

Is there a way to trigger Vuelidate to re-check a validation? For example, I have a form field where users can input the name of a remote directory. There is a Vuelidate validation in place that communicates with the server to verify if the directory exis ...