/
Add TopoJSON data to the map.html
187 lines (154 loc) · 9.25 KB
/
Add TopoJSON data to the map.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
<!DOCTYPE html>
<html lang="en">
<head>
<title>Add TopoJSON data to the map - Azure Maps Web SDK Samples</title>
<meta charset="utf-8" />
<link rel="shortcut icon" href="/favicon.ico"/>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<meta name="description" content="This sample shows how to add TopoJSON data to the map, by converting it into GeoJSON in a Web Worker so that map can easily render it." />
<meta name="keywords" content="Microsoft maps, map, gis, API, SDK, TopoJSON" />
<meta name="author" content="Microsoft Azure Maps" /><meta name="version" content="1.0" />
<meta name="screenshot" content="screenshot.jpg" />
<!-- Add references to the Azure Maps Map control JavaScript and CSS files. -->
<link href="https://atlas.microsoft.com/sdk/javascript/mapcontrol/3/atlas.min.css" rel="stylesheet" />
<script src="https://atlas.microsoft.com/sdk/javascript/mapcontrol/3/atlas.min.js"></script>
<!-- Load in Catiline.js library which makes it easier to work with web workers. -->
<script src="/lib/catiline/dist/catiline.min.js"></script>
<script>
var map, datasource, popup, topojsonWorker;
function GetMap() {
//Initialize a map instance.
map = new atlas.Map('myMap', {
style: 'grayscale_dark',
view: 'Auto',
//Add authentication details for connecting to Azure Maps.
authOptions: {
//Use Azure Active Directory authentication.
authType: 'anonymous',
clientId: 'e6b6ab59-eb5d-4d25-aa57-581135b927f0', //Your Azure Maps client id for accessing your Azure Maps account.
getToken: function (resolve, reject, map) {
//URL to your authentication service that retrieves an Azure Active Directory Token.
var tokenServiceUrl = "https://samples.azuremaps.com/api/GetAzureMapsToken";
fetch(tokenServiceUrl).then(r => r.text()).then(token => resolve(token));
}
//Alternatively, use an Azure Maps key. Get an Azure Maps key at https://azure.com/maps. NOTE: The primary key should be used as the key.
//authType: 'subscriptionKey',
//subscriptionKey: '[YOUR_AZURE_MAPS_KEY]'
}
});
//Wait until the map resources are ready.
map.events.add('ready', function () {
popup = new atlas.Popup();
//Create a data source to add your data to.
datasource = new atlas.source.DataSource();
map.sources.add(datasource);
//Add a layer for the polygon areas and add it below the map labels.
var polygonLayer = new atlas.layer.PolygonLayer(datasource);
map.layers.add(polygonLayer, 'labels');
//Add a line layer for the polygon outlines.
map.layers.add(new atlas.layer.LineLayer(datasource, null, {
strokeColor: 'white'
}));
map.events.add('click', polygonLayer, featureClicked);
//Create a web worker that uses the topojson-client library.
var wfunc = function (base, cb) {
//Import the topojson-client library.
importScripts('https://unpkg.com/topojson-client@3');
//Download the topojson data.
fetch(base)
.then(response => response.json())
.then(function (topology) {
//Extract all layers from the TopoJSON topology and convert into GeoJSON.
var geojson = [];
Object.keys(topology.objects).forEach(function (val, idx, arr) {
var d = topojson.feature(topology, topology.objects[val]);
if (d.type === 'FeatureCollection') {
geojson = geojson.concat(d.features);
} else {
geojson.push(d);
}
});
cb(geojson);
});
};
topojsonWorker = cw({ data: wfunc }, 2);
});
}
function loadTopoJsonFile(url) {
datasource.clear();
popup.close();
document.getElementById('loadingIcon').style.display = '';
topojsonWorker.data(cw.makeUrl(url)).then(function (geojson) {
//Add the GeoJSON to the map.
datasource.add(geojson);
//Set the map view over the data.
map.setCamera({
bounds: atlas.data.BoundingBox.fromData(geojson)
});
document.getElementById('loadingIcon').style.display = 'none';
});
}
function featureClicked(e) {
//Make sure the event occurred on a shape feature.
if (e.shapes && e.shapes.length > 0) {
//By default, show the popup where the mouse event occurred.
var pos = e.position;
var offset = [0, 0];
var properties;
if (e.shapes[0] instanceof atlas.Shape) {
properties = e.shapes[0].getProperties();
//If the shape is a point feature, show the popup at the points coordinate.
if (e.shapes[0].getType() === 'Point') {
pos = e.shapes[0].getCoordinates();
offset = [0, -18];
}
} else {
properties = e.shapes[0].properties;
//If the shape is a point feature, show the popup at the points coordinate.
if (e.shapes[0].type === 'Point') {
pos = e.shapes[0].geometry.coordinates;
offset = [0, -18];
}
}
//Update the content and position of the popup.
popup.setOptions({
//Create a table from the properties in the feature.
content: atlas.PopupTemplate.applyTemplate(properties),
position: pos,
pixelOffset: offset
});
//Open the popup.
popup.open(map);
}
}
</script>
</head>
<body onload="GetMap()">
<div id="myMap" style="position:relative;width:100%;min-width:290px;height:600px;"></div>
<div style="position:absolute;top:10px;left:10px;background-color:white;border-radius:5px;padding:5px;">
Load TopoJSON:<br />
<input type="button" onclick="loadTopoJsonFile('/data/topojson/Spain_Municipalities.json')" value="Spain Municipalities (1.5MB)" /><br />
<input type="button" onclick="loadTopoJsonFile('/data/topojson/Brazil_Municipalities.json')" value="Brazil Municipalities (3.5MB)" /><br />
<input type="button" onclick="loadTopoJsonFile('/data/topojson/zips_us_topo.json')" value="US Zip Codes (5.3MB)" /><br />
<input type="button" onclick="loadTopoJsonFile('/data/topojson/neilsen_dma.json')" value="Neilsen DMA (700KB)" /><br />
<input type="button" onclick="loadTopoJsonFile('/data/topojson/sandiego_zoning_datasd.topojson')" value="San Diego Zoning data (7.3MB)" /><br />
<input type="button" onclick="loadTopoJsonFile('/data/topojson/England_Electoral_Wards.json')" value="England Electoral Wards (4.3MB)" /><br />
<input type="button" onclick="loadTopoJsonFile('/data/topojson/zip-code-level-2017-topojson.json')" value="US Zip Code Tabulation Areas 2018 (35MB)" />
</div>
<img id="loadingIcon" src="/images/loadingIcon.gif" title="Loading" style="position:absolute;left:calc(50% - 25px);top:250px;display:none;" />
<fieldset style="width:calc(100% - 30px);min-width:290px;margin-top:10px;">
<legend>Add TopoJSON data to the map</legend>
This sample shows how to add TopoJSON data to the map, by converting it into GeoJSON in a Web Worker so that map can easily render it.
TopoJSON data is an extension of GeoJSON that encodes topology.
This is ideal for reducing the file size of polygon data sets that that share edges.
This sample uses the open source <a href="https://github.com/topojson/topojson-client">topojson-client library</a> for converting the decoding the TopoJSON data into GeoJSON which can be easily add to the map.
It also makes use of the open source <a href="http://catilinejs.com/">Catiline.js</a> library which makes working with web workers easier.
<br />
<br />
<b>Note:</b> Not all file and mime types are enabled in all servers. If using .NET, it is recommended to add the following to the web.config file:
<br />
<br />
<system.webServer><br /> <staticContent><br /> <mimeMap fileExtension=".topojson" mimeType="application/json" /><br /> </staticContent><br /><system.webServer>
</fieldset>
</body>
</html>