Move a pin on Mapbox

I have a question regarding my map markers:

https://i.sstatic.net/2HndV.png

Currently, the center of the blue markers align with my desired coordinates. Is there a way to adjust the markers slightly upwards so that the tip sits exactly on my specified point, rather than being centered?

The code I am using for the markers is quite standard, similar to what can be found in the mapbox documentation. Here's an example:

await nodeList.map((node) => {
    map.addSource(node.name, {
        'type': 'geojson',
        'data': {
            'type': 'FeatureCollection',
            'features': [{
                'type': 'Feature',
                'geometry': {
                    'type': 'Point',
                    'coordinates': [node.longitude, node.latitude]
                },
                'properties': {}
            }]
        }
    });
    map.addLayer({
        'id': node.name,
        'type': 'symbol',
        'source': node.name,
        'layout': {
            'icon-image': 'custom-marker',
            'text-offset': [0, 1.25],
            'text-anchor': 'top'
        }
    });
});

Answer №1

When referring to the symbol layers in the documentation, you will discover an option called icon-anchor. This attribute allows you to specify which part of the Marker should be positioned closest to the coordinate set. The available options include 'center', 'top', 'bottom', 'left', 'right', 'top-left', 'top-right', 'bottom-left', and 'bottom-right'.

The default value is 'center', but if you specify icon-anchor: bottom in your anchor options, it will be positioned correctly.

await nodeList.map((node) => {
    map.addSource(node.name, {
        'type': 'geojson',
        'data': {
            'type': 'FeatureCollection',
            'features': [{
                'type': 'Feature',
                'geometry': {
                    'type': 'Point',
                    'coordinates': [node.longitude, node.latitude]
                },
                'properties': {}
            }]
        }
    });
    map.addLayer({
        'id': node.name,
        'type': 'symbol',
        'source': node.name,
        'layout': {
            'icon-image': 'custom-marker',
            'icon-anchor': 'bottom',
            'text-offset': [0, 1.25],
            'text-anchor': 'top'
        }
    });
});

Answer №2

In the style definition of Mapbox GL, there is a pre-existing layout option called "icon-offset" that can be utilized for both basic styling and data-driven styling purposes. As far as I know, you need to specify an image in order to effectively use this feature. Here is a sample implementation extracted from a React Mapbox GL application:

    <Source
      id="locations"
      type="geojson"
      data={filteredData}
      generateId={true}
    />
    <Layer
      source="locations"
      id="locations"
      type="symbol"          
      layout={{
        "icon-image": "pin",
        "icon-offset": 0.3,
        "icon-size": 0.25,
        "icon-allow-overlap": true,
      }}          
    />

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

Verify if the date string includes the day

Here's the scenario: a user clicks on one of two links, either 2012/10, or 2012/10/15. I am extracting the day value from the link to pass it onto an AJAX request that will change days on an archive page. Is using a regular expression like /\d{ ...

I'm having trouble locating the airtable module, even after I successfully ran npm install airtable

Currently attempting to integrate the airtable api into my website's backend using node.js. However, upon writing var Airtable = require('airtable'); and running the file with node [filepath], I encounter an error in the command prompt: ...

What action is triggered on an Apple iPhone when a notification is tapped?

Currently, I am working on a React application and testing it on an Apple mobile phone. One issue I encountered is that when I receive an SMS, the number appears as a suggestion above the keyboard. I want to be able to tap on this number and have it automa ...

Having trouble with this ajax code? It's not showing up dynamically

There is a live search bar in my project where the results are filtered as the user types. Each result is a clickable link that should load on the same page, but I'm facing some issues with the implementation. The search functionality is powered by a ...

What is the best method for communicating between windows in an electron application?

As I embark on the journey of creating my first electron app, I kindly ask for your understanding :) Upon clicking a button in the main Window, a new window should open displaying a JSON string. This action is captured by ipcMain: ipcMain.on("JSON:ShowPa ...

Utilizing Firebase messaging onMessage function is exclusively enabled within a window environment

Incorporating Firebase Cloud Messaging into my project allowed me to send and receive push notifications successfully. While I can receive the push notifications, unfortunately, I am encountering issues with getting the notification events to function prop ...

Error encountered while attempting to save a Mongoose post on Heroku, although it is successful

My aim is to post to my MongoDB Atlas database using node, express, mongoose, and Heroku. While a Postman POST request with Raw JSON body: { "title": "heroku post", "description": "post me plsssss" } works f ...

Uncovering the Mystery: Extracting a Video Thumbnail from Brightcove Videos

Is there a way to extract the video thumbnail from Brightcove Video? <x:out select="$item/description" escapeXml="false" /> At the moment, the thumbnail is being retrieved within the description. ...

Is there a Rust secp256k1 alternative to the `crypto::ECDH::computeSecret()` function in NodeJS?

After developing a functional NodeJS/Javascript function, I am now intrigued by the idea of achieving similar results using the Rust secp256k1 library: /* * Calculate the Symmetric Key from the Public and Secret keys from two * different key pairs. * ...

Exploring discrepancies between two tables with the power of Javascript

const firstTable = document.getElementById('table_1') const secondTable = document.getElementById('table_2') const rows1 = firstTable.rows const rows2 = secondTable.rows for (let i = 0; i < rows1.length; i++) { for (let x in rows ...

I'm interested in developing a React function that generates recipe components based on a set of instructions provided in an array, along with a separate parameter specifying the recipe name

I am currently immersed in the book "Learning React" written by O'Reilly. The book mentions a method of creating components by using a function known as the "component creating function". It advises supplying the necessary parameters as the second par ...

Where do the props in React come from?

In my quest to learn React. I perused w3school's guide, but alas, the specific case I seek was not found. Even Google failed me in this pursuit, leading me here to pose my question. Behold, the code in question: <FooComponent foo="bar"> {( ...

What's the best way to group rows in an angular mat-table?

I am working on a detailed mat-table with expanded rows and trying to group the rows based on Execution Date. While looking at this Stackblitz example where the data is grouped alphabetically, I am struggling to understand where to place the group header c ...

Verifying with VueJS and Jest: How to test if a component's method calls an imported function

I've created a VueJS 2 component that has the following structure: <template> <div> <button @click="onFavorite"> Add to favorites </button> </div> </template> <script> import { tra ...

Tips on making a fresh form appear during the registration process

After clicking on a submit button labeled as "continue" within a form, a new form will appear for you to complete in order to continue the registration process. ...

Unit tests manipulating JavaScript functions to return undefined values

Currently, I am in the process of testing some JavaScript functions within a larger React application. These functions heavily utilize the module pattern, which leads me to believe that my misunderstanding lies within this pattern. The script I am testing ...

Creating a function that writes to a file by utilizing the data input from

After running the provided code snippet, it successfully works in a standalone project. However, I am interested in making modifications to replace the variable "sample_text" with an output that is displayed in the terminal instead of being hardcoded int ...

Transforming jQuery Object into a String after making an AJAX request

If I were to submit a form with some text in the value of user_input, let's say "I am free," through AJAX, and it comes back to me as a string. Once it becomes an Object, how could I convert it back into a string format? Thanks, <!DOCTYPE HTML> ...

Adjusting the position of a stationary element when the page is unresponsive and scrolling

Managing a large web page with extensive JavaScript functionality can be challenging, especially when dealing with fixed position elements that update based on user scroll behavior. A common issue that arises is the noticeable jumping of these elements whe ...

utilize jQuery to load webpage with an HTML dropdown element

Querying the Campaigns: // Getting the campaigns $campaigns = $wpdb->get_results( "SELECT * FROM tbl_campaigns ORDER BY campaignID DESC", OBJECT_K ); // Displaying the Cam ...