Dynamic markers with Mapbox in Meteor.js

Recently, I was able to dynamically set the mapbox viewpoint by passing a street address from my database to the geocoder.

However, I now want to take it a step further and add a marker at the location of the address instead of just setting the map view.

Template.vendorPage.rendered = function(){

    // Retrieve address from database using ID
    var getAddress = function(){
        var pathname =location.pathname.split("/"); 
        var thisId = pathname[2]; 
        return Vendors.findOne({_id: thisId}).address;
    }
    // Set variable to the address function
    var thisAddress = getAddress(); 

    // Draw the mapbox
    L.mapbox.accessToken = '<My Token Here>';
    var geocoder = L.mapbox.geocoder('mapbox.places-v1'),
        map = L.mapbox.map('map', 'alexnetsch.j786e624');

    geocoder.query(thisAddress, showMap);

    function showMap(err, data) {
        if (data.lbounds) {
            map.fitBounds(data.lbounds);
        } else if (data.latlng) {
            map.setView([data.latlng[0], data.latlng[1]], 16);
        }
    }

}

I have spent hours trying to implement markers without success. I would like to simply pass the address to the marker function.

Rather than just setting the viewport, I am looking to zoom in and center the map around my marker.

Here is an example from the documentation, but without geocoding the location.

L.mapbox.accessToken = 'pk.eyJ1IjoiYWxleG5ldHNjaCIsImEiOiJsX0V6Wl9NIn0.i14NX5hv3bkVIi075nOM2g';
var map = L.mapbox.map('map', 'examples.map-20v6611k')
    .setView([38.91338, -77.03236], 16);

L.mapbox.featureLayer({
    type: 'Feature',
    geometry: {
        type: 'Point',
        coordinates: [
          -77.03221142292,
          38.913371603574 
        ]
    },
    properties: {
        title: 'Peregrine Espresso',
        description: '1718 14th St NW, Washington, DC',
        'marker-size': 'large',
        'marker-color': '#BE9A6B',
        'marker-symbol': 'cafe'
    }
}).addTo(map);

Answer №1

Finally figured it out!

Template.vendorPage.rendered = function(){
    getAddress = function(){
        path = location.pathname.split("/"); 
        id = path[2]; 
        return Vendors.findOne({_id: id}).address
    }

    address = getAddress(); 

    //visualize the mapbox
    L.mapbox.accessToken = 'pk.eyJ1IjoiYWxleG5ldHNjaCIsImEiOiJsX0V6Wl9NIn0.i14NX5hv3bkVIi075nOM2g';
    var geocoder = L.mapbox.geocoder('mapbox.places-v1'),
        map = L.mapbox.map('map', 'alexnetsch.j786e624');

    geocoder.query(address, showMap);

    function showMap(err, data) {
        if (data.lbounds) {
            map.fitBounds(data.lbounds);
        } else if (data.latlng) {
            map.setView([data.latlng[0], data.latlng[1]], 16);
        }
    }

    var addMarker;
    addMarker = function(geocoder, map, placeName) {
      return geocoder.query(placeName, function(error, result) {
        var marker;
        marker = L.marker(result.latlng);
        return marker.addTo(map);
      });
    };

    addMarker(geocoder, map, address);

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

Tips for implementing $routeProvider's resolve function in electron-angular-boilerplate

I am encountering an issue with loading JSON data before entering the main controller in my project. Using this project as a template, I made alterations to only dist/app/home/home.js where the changes were implemented: angular.module('WellJournal&a ...

Having trouble linking a sqlite file in your tauri + vue project?

After successfully installing tauri-plugin-sql by adding the specified content to src-tauri/Cargo.toml : [dependencies.tauri-plugin-sql] git = "https://github.com/tauri-apps/plugins-workspace" branch = "v1" features = ["sqlite" ...

Different choices for data attributes in React

Recently, I downloaded a new app that requires multiple API calls. The first API call retrieves 20 Objects, each with its own unique ID. The second API call is made based on the IDs from the first call. To display this data in my component: <div> ...

Uncover concealed images by adjusting the opacity of the cover image during a mouse movement event

As I was working on a project, I came up with a simple code to adjust the opacity of a cover image in order to reveal a hidden image underneath. The setup involved two canvas elements stacked on top of each other, both measuring 500x500 pixels and containi ...

Triggering an event when selecting options in dropdown menus on Firefox

Currently, I am facing the following scenario: I have a single select box along with a tooltip that is displayed when the user clicks on the box to choose an option. The tooltip can easily be shown using CSS (select:focus ~ .tooltip) or jQuery by utilizin ...

Checking the submission text field with Javascript is being confirmed

It seems I've made a small mistake somewhere, and I would appreciate it if someone could help me find it. I'm attempting to validate a postcode in a form field once it's been entered. I've tried similar code in PHP, and it works fine, b ...

Experience seamless one-to-many broadcasting with WebRTC/Kurento, featuring server-side recording capabilities

I am currently exploring Kurento to determine if it fits my needs. I am interested in developing a mobile application that can record and stream video to a server in real-time, with the server saving the video on its file system as it is being transmitted. ...

Setting the current date of a jQuery datepicker to the value of an input tag

I am looking to assign a value to an input tag that has a datepicker attached to it. Upon initialization of the datepicker, I want to set this value. Below is a hypothetical example of what I am trying to achieve: HTML: <input id="test" value="">&l ...

What is the button that switches the bootstrap modal?

With my bootstrap modal form, I have multiple buttons that trigger it as shown below: <a href="javascript:void(0)" data-toggle="modal" data-target="#specialoffer"> <button class="green full" id="button1">Ask Question</button> </a& ...

Error encountered: Attempting to use a class as a function in vue-socket.io is not permitted

I am developing a Vue chrome extension where I am attempting to implement web sockets using vue-socket.io. I have followed the basic instructions on deploying a node server with express and socket.io on Heroku, but I am encountering issues with the conne ...

Adding the unzip feature is not within my capabilities

I am a novice Japanese web developer. Unfortunately, my English skills are not great. I apologize for any inconvenience. I am interested in utilizing this specific module: https://www.npmjs.com/package/unzip To do so, I executed the following commands ...

Contrasting an array of items with an array of Objects

I need to match the values in an array called ingredientName with a corresponding array of objects. Here is how they look: const ingredientName = ['chicken', 'cheese', 'tomato', 'lettuce']; let imageObjects = [ { ...

The technique of binding methods in React

When working with React.js, it's recommended to define your method binding in the constructor for better performance. Here's an example: constructor(props){ this.someFunction = this.someFunction.bind(this); } This approach is more efficient t ...

The THREE.js WebGLRenderer canvas captures the 'click' mouse event

After including the domElement (canvas) from THREE.js WebGLRenderer in my document, I noticed that the 'click' mouse event no longer triggers when clicking on the container element containing the canvas. Is there a method to prevent the canvas f ...

What issues can be identified in this ajax.js script?

This particular function is designed to verify the existence or availability of a user login, yet even when the user database table is empty, the form consistently indicates that there is a duplicate entry. As a result, the submit button disappears. What c ...

Ways to pause a nested iteration while the inner loop is waiting for a response?

My issue involves creating a function in JavaScript that can generate correct answers for an online multiple choice questionnaire form. The goal is to iterate through the questions and identify the correct responses. To simplify things, I will focus on ha ...

Sending data from Node.JS to an HTML document

Currently, I am working on parsing an array fetched from an API using Node.js. My goal is to pass this array as a parameter to an HTML file in order to plot some points on a map based on the API data. Despite searching through various answers, none of them ...

Convert a multidimensional array into a string using JavaScript

Currently, I'm in the process of generating an invoice for a collection of books and my intent is to submit it using ajax. However, when attempting to json encode the array of books within the invoice, I am encountering a setback where the value keeps ...

use ajax to dynamically load a section of the webpage based on filter criteria

I need to implement a search filter using 3 checkboxes. The search results will be displayed in the div with the id=posts_results <div class="checkbox"> <label><input type="checkbox" id="id1" class="typePost" value="En groupe"> ...

Receiving multiple NodeJS Responses through AJAX for a single request

I have been working on a WebApp that involves heavy AJAX calls from the frontend and NodeJS Express at the backend. Here is a glimpse of my Frontend Code- Below is the global AJAX function I consistently use in all my projects: function _ajax(params = {}, ...