Skip to content

Instantly share code, notes, and snippets.

@danicarrion
Last active October 17, 2016 15:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danicarrion/6a746f0fa24c6dfe749dd38d7a19b89e to your computer and use it in GitHub Desktop.
Save danicarrion/6a746f0fa24c6dfe749dd38d7a19b89e to your computer and use it in GitHub Desktop.
CARTO + Openlayers + MVT example
<!doctype html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>CARTO + Openlayers + MVT example</title>
<link rel="stylesheet" href="https://openlayers.org/en/v3.18.2/css/ol.css" type="text/css" />
<script src="https://openlayers.org/en/v3.18.2/build/ol.js"></script>
<style>
body {
margin: 0px;
border: 0px;
padding: 0px;
}
#map {
height: 100%;
width: 100%;
position: absolute;
}
</style>
</head>
<body>
<div id="map"></div>
<!-- openlayers -->
<script src="https://openlayers.org/en/v3.18.2/build/ol.js"></script>
<!-- CARTO core -->
<script src="http://libs.cartocdn.com/cartodb.js/v3/3.15/cartodb.core.js"></script>
<script>
var cartoLayer = {
user_name: "dcarrion",
sublayers: [
{
sql: "SELECT * FROM tornados",
cartocss: "#tornados {marker-fill: #ff0000}",
}
]
};
/* Get the URL for the MVT tile service for this layer */
cartodb.Tiles.getTiles(cartoLayer, function(result, err) {
var tiles = result.tiles.map(function(tileUrl) {
return tileUrl
.replace('{s}', 'a')
.replace(/\.png/, '.mvt');
})[0];
// some styles for the vector layer
var fill = new ol.style.Fill({
color: 'rgba(0,0,0,0.2)'
});
var stroke = new ol.style.Stroke({
color: 'rgba(0,0,0,0.4)'
});
var circle = new ol.style.Circle({
radius: 6,
fill: fill,
stroke: stroke
});
var vectorStyle = new ol.style.Style({
fill: fill,
stroke: stroke,
image: circle
});
/* Add CARTO layers */
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.XYZ({
attributions: [
new ol.Attribution({
html: '© <a href="http://cartodb.com/attributions">CartoDB</a> © <a href="http://www.openstreetmap.org/copyright">OpenStreetMap contributors</a>'
})
],
url:'http://{1-4}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png'
})
}),
new ol.layer.VectorTile({
source: new ol.source.VectorTile({
format: new ol.format.MVT(),
tileGrid: ol.tilegrid.createXYZ({maxZoom: 22}),
tilePixelRatio: 16,
url: tiles
}),
style: vectorStyle
})
],
view: new ol.View({
center: ol.proj.fromLonLat([-74.00976419448853, 40.70531887544228]),
zoom: 4
})
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment