1 |
|
2 | goog.require('ol.Map');
|
3 | goog.require('ol.View');
|
4 | goog.require('ol.extent');
|
5 | goog.require('ol.layer.Image');
|
6 | goog.require('ol.layer.Tile');
|
7 | goog.require('ol.proj');
|
8 | goog.require('ol.source.ImageCanvas');
|
9 | goog.require('ol.source.Stamen');
|
10 |
|
11 |
|
12 | var 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 |
|
30 |
|
31 | d3.json('data/topojson/us.json', function(error, us) {
|
32 | var features = topojson.feature(us, us.objects.counties);
|
33 |
|
34 | |
35 |
|
36 |
|
37 |
|
38 |
|
39 |
|
40 |
|
41 |
|
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 | });
|