UNPKG

2.93 kBJavaScriptView Raw
1// NOCOMPILE
2goog.require('ol.Map');
3goog.require('ol.View');
4goog.require('ol.extent');
5goog.require('ol.layer.Image');
6goog.require('ol.layer.Tile');
7goog.require('ol.proj');
8goog.require('ol.source.ImageCanvas');
9goog.require('ol.source.Stamen');
10
11
12var map = new ol.Map({
13 layers: [
14 new ol.layer.Tile({
15 source: new ol.source.Stamen({
16 layer: 'watercolor'
17 })
18 })
19 ],
20 target: 'map',
21 view: new ol.View({
22 center: ol.proj.fromLonLat([-97, 38]),
23 zoom: 4
24 })
25});
26
27
28/**
29 * Load the topojson data and create an ol.layer.Image for that data.
30 */
31d3.json('data/topojson/us.json', function(error, us) {
32 var features = topojson.feature(us, us.objects.counties);
33
34 /**
35 * This function uses d3 to render the topojson features to a canvas.
36 * @param {ol.Extent} extent Extent.
37 * @param {number} resolution Resolution.
38 * @param {number} pixelRatio Pixel ratio.
39 * @param {ol.Size} size Size.
40 * @param {ol.proj.Projection} projection Projection.
41 * @return {HTMLCanvasElement} A canvas element.
42 */
43 var canvasFunction = function(extent, resolution, pixelRatio,
44 size, projection) {
45 var canvasWidth = size[0];
46 var canvasHeight = size[1];
47
48 var canvas = d3.select(document.createElement('canvas'));
49 canvas.attr('width', canvasWidth).attr('height', canvasHeight);
50
51 var context = canvas.node().getContext('2d');
52
53 var d3Projection = d3.geo.mercator().scale(1).translate([0, 0]);
54 var d3Path = d3.geo.path().projection(d3Projection);
55
56 var pixelBounds = d3Path.bounds(features);
57 var pixelBoundsWidth = pixelBounds[1][0] - pixelBounds[0][0];
58 var pixelBoundsHeight = pixelBounds[1][1] - pixelBounds[0][1];
59
60 var geoBounds = d3.geo.bounds(features);
61 var geoBoundsLeftBottom = ol.proj.transform(
62 geoBounds[0], 'EPSG:4326', projection);
63 var geoBoundsRightTop = ol.proj.transform(
64 geoBounds[1], 'EPSG:4326', projection);
65 var geoBoundsWidth = geoBoundsRightTop[0] - geoBoundsLeftBottom[0];
66 if (geoBoundsWidth < 0) {
67 geoBoundsWidth += ol.extent.getWidth(projection.getExtent());
68 }
69 var geoBoundsHeight = geoBoundsRightTop[1] - geoBoundsLeftBottom[1];
70
71 var widthResolution = geoBoundsWidth / pixelBoundsWidth;
72 var heightResolution = geoBoundsHeight / pixelBoundsHeight;
73 var r = Math.max(widthResolution, heightResolution);
74 var scale = r / (resolution / pixelRatio);
75
76 var center = ol.proj.transform(ol.extent.getCenter(extent),
77 projection, 'EPSG:4326');
78 d3Projection.scale(scale).center(center)
79 .translate([canvasWidth / 2, canvasHeight / 2]);
80 d3Path = d3Path.projection(d3Projection).context(context);
81 d3Path(features);
82 context.stroke();
83
84 return canvas[0][0];
85 };
86
87 var layer = new ol.layer.Image({
88 source: new ol.source.ImageCanvas({
89 canvasFunction: canvasFunction,
90 projection: 'EPSG:3857'
91 })
92 });
93 map.addLayer(layer);
94});