原文链接及内容

运行界面

此示例演示如何在地图中显示来自 Google 的地图切片数据。要使用 Google Map Tiles API,你需要设置 Google Cloud项目并为您的应用程序创建API秘钥,有关说明请参阅Map Tiles API documentation。关于ol/source/Google数据源对象可以用于配置切片图层对象,即通过将属性传递给用于创建会话令牌请求(session token request)的构造函数以访问切片数据。mapType属性默认值为roadmap,并且可以被更改为任何支持的地图类型。

注:创建API秘钥竟然需要信用卡就算了,还不支持大陆地区🤣,不过也正常。

main.js代码如下:

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
import Google from 'ol/source/Google.js';
import Layer from 'ol/layer/WebGLTile.js';
import Map from 'ol/Map.js';
import View from 'ol/View.js';

function showMap(key) {
const source = new Google({
key,
scale: 'scaleFactor2x',
highDpi: true,
});

source.on('change', () => {
if (source.getState() === 'error') {
alert(source.getError());
}
});

const map = new Map({
layers: [new Layer({source})],
target: 'map',
view: new View({
center: [0, 0],
zoom: 2,
}),
});
}

document.getElementById('key-form').addEventListener('submit', (event) => {
showMap(event.target.elements['key'].value);
});

界面布局文件index.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Google Maps</title>
<link rel="stylesheet" href="node_modules/ol/ol.css">
<style>
.map {
width: 100%;
height: 400px;
}
</style>
</head>
<body>
<div id="map" class="map">
<dialog open>
<form method="dialog" id="key-form">
<label>Your API key
<input type="password" name="key">
</label>
<button type="submit">show map</button>
</form>
</dialog>
</div>


<script type="module" src="main.js"></script>
</body>
</html>