Multiple CartoDB Named Maps on One Leaflet Map
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Document</title> | |
<link rel="stylesheet" href="http://libs.cartocdn.com/cartodb.js/v3/3.15/themes/css/cartodb.css" /> | |
<style> | |
#map, html, body { | |
height:100%; | |
width:100%; | |
} | |
</style> | |
</head> | |
<body> | |
<div id="map"> | |
</div> | |
<script src="http://libs.cartocdn.com/cartodb.js/v3/3.15/cartodb.js"></script> | |
<script src = "https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.2.0/mustache.js"></script> | |
<script> | |
// So it turns out that if you use createLayer() twice on the same map with layers that require different auth_token parameters, it will use the same one for both and one of the maps won't load. I think this is a bug in cartodb.js | |
// Below is how to add two cartoDB UI-created named maps with auth tokens. | |
var map = new L.Map('map', { | |
center: [0,0], | |
zoom: 2 | |
}); | |
L.tileLayer('http://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png',{ | |
attribution: '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, © <a href="http://cartodb.com/attributions">CartoDB</a>' | |
}).addTo(map); | |
var layerSource1 = { | |
type: "namedmap", | |
auth_token: "1292efe9e4b91a7a4ca2dfa87f6277693681e82a5ab5cc62ebc13f992283863e", | |
user_name: "chriswhong", | |
filter: "mapnik", | |
named_map: { | |
name: "tpl_2d3816ca_8985_11e5_a172_0ecd1babdde5", | |
} | |
} | |
var layerSource2 = { | |
type: "namedmap", | |
auth_token: "05860d727e334e304a331aa28cd678d0d40ea4eeaae6584ab2f9ea6b5e4a123f", | |
user_name: "chriswhong", | |
filter: "mapnik", | |
named_map: { | |
name: "tpl_037cd332_8987_11e5_9e0b_0e5db1731f59", | |
} | |
} | |
addLayer(layerSource1); | |
addLayer(layerSource2); | |
function addLayer(layerSource) { | |
$.ajax({ | |
url: Mustache.render('https://{{user_name}}.cartodb.com/api/v1/map/named/{{named_map.name}}?auth_token={{auth_token}}', layerSource), | |
type:"POST", | |
contentType:"application/json; charset=utf-8", | |
dataType:"json", | |
success: function(data){ | |
console.log(data); | |
var url = Mustache.render('https://cartocdn-ashbu.global.ssl.fastly.net/{{user_name}}/api/v1/map/{{layergroupid}}/{z}/{x}/{y}.png?auth_token={{auth_token}}',{ | |
user_name: layerSource.user_name, | |
layergroupid: data.layergroupid, | |
auth_token: layerSource.auth_token | |
}); | |
L.tileLayer(url).addTo(map); | |
} | |
}) | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment