3
votes

I'm trying to toggle the display of a CartoDb layer on a Leaflet map. I've been able to load the layer using this code:

       var layerUrl = 'http://ronh-aagis.cartodb.com/api/v1/viz/rotaryclubs_geo2/viz.json';

       var clubPts = cartodb.createLayer(map, layerUrl, {
           // The ST_AsGeoJSON(ST_Simplify(the_geom,.01)) as geometry will store a simplified GeoJSON representation of each polygon as an attribute we can pick up on hover

           query: 'select  *, ST_AsGeoJSON(the_geom) as geometry from {{table_name}}',

           interactivity: 'cartodb_id, geometry'
       })

                          .on('done', function(layer) {
                              map.addLayer(layer);

                          layer.on('featureOver', function(e, pos, latlng, data) {
                       $('.leaflet-container').css('cursor','pointer');

                       if (data.cartodb_id != point.cartodb_id) {
                           drawHoverPoint(data);
                       }
                       cartodb.log.log(pos, data);
                   });

                   layer.on('featureOut', function(e, pos, latlng, data) {
                       $('.leaflet-container').css('cursor','default')
                       removePoint();
                   });

                   layer.on('error', function(err) {
                       cartodb.log.log('error: ' + err);
                   });

               }).on('error', function() {
                   cartodb.log.log("some error occurred");
               });

Yet when I try to add this layer to a Layer Control:

       var clubs = new L.LayerGroup();
       clubs.addLayer(clubPts);

I get an "Uncaught TypeError: Object # has no method 'onAdd'" error.

Any thoughts? Thanks!

1
Are you trying to load both leaflet.js and cartodb.js in your HTML header? This looks like the sort of error you'd get if you loaded cartodb.js first, and then overrode part of it with leaflet.js.Martin Burch

1 Answers

2
votes

A great way to reduce complexity and get up to speed quickly here would be using an already-built Leaflet plugin, like Vector Layers, that has built-in CartoDB support already. Take a look at the demo here. http://jasonsanford.github.io/leaflet-vector-layers/demos/cartodb/