Search code examples
javascriptleaflettabletop.js

How to add markers to leaflet map with tabletop.js?


I'm using this quite nice guide to add markers from a Google sheet to a basic leaflet.js map: https://rdrn.me/leaflet-maps-google-sheets/

The problem is, using these code snippets here i get all the data logged and returned in the console, but none of the points appear on the map itself.

This is probably some really basic JavaScript issue that i'm not able to see. Sorry, still learning.

Here's a jfiddle, linking to a demo sheets with one marker point

https://jsfiddle.net/xfs19cz7/1/

with the map part:

function init() {
    Tabletop.init({
        key: '*url to gsheets here*',
        callback: myFunction,
        simpleSheet: true
    })
}

window.addEventListener('DOMContentLoaded', init)

function myFunction(data, tabletop) {
    console.log(data);
}


var map = L.map('map-div').setView([64.6220498,25.5689638], 5);
var basemap = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: 'Basemap (c) <a href="http://openstreetmap.org">OpenStreetMap</a>',
        minZoom: 5,
        maxZoom: 18
    });
basemap.addTo(map);

function addPoints(data, tabletop) {
    for (var row in data) {
        var marker = L.marker([
            data[row].Latitude,
            data[row].Longitude
        ]).addTo(map);
        marker.bindPopup('<strong>' + data[row].Info + '</strong>');
    }
}

This should add one point to a basic map. Now actually the map is not at all rendered, and no marker shows up. I can't find any issues in the code making the map show up blank, but there probably are some.

The marker from gsheets is however logged in the console, i suspect there is something missing in my code relating to really basic javascript functions / looping / sloppy syntax.

Also tried the init() and addPoints(data, tabletop) parts to a map i had where the map with the same basemap link, which rendereded OK. Adding this still left the map rendering, but no markers showed up. Again, the gsheets was loaded as an array of objects.

Could anyone point me to this, probably very basic, issue in the code?

edit:

callback: myFunction, 

line above needs to be changed to

callback: addPoints,

also, init function needs to be called and position set to absolute. Thanks for the working fiddle in answer marked as correct below.


Solution

  • Fixes

    • Try setting map position absolute
    • calling the init() function

    Working fiddle