一 创建地图
1. api对比
| OpenLayers | Leaflet | Mapbox |
|---|---|---|
| new ol.Map({...options}) | L.map("id", {...options}) | new mapboxgl.Map({...options}) |
2. 代码与结果展示
⑴ OpenLayers
① 代码
<head>
...
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ol/ol.css" type="text/css">
<script src="https://cdn.jsdelivr.net/npm/ol/ol.js"></script>
...
<style>
/*地图显示需要DOM元素一个宽高 */
#map {
width: 100vw;
height: 100vh;
}
</style>
</head>
<body>
<!-- DOM挂载点 -->
<div id="map"></div>
<script>
const map = new ol.Map({
//挂载到id="map"的元素上
target: 'map',
//地图初始图层
layers: [
new ol.layer.Tile({
source: new ol.source.OSM(),
}),
],
//地图初始视角
view: new ol.View({
center: [116.4, 39.9],
zoom: 8,
projection: 'EPSG:4326',
}),
})
</script>
</body>
② 结果

⑵ Leaflet
① 代码
<head>
...
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.3/dist/leaflet.css"/>
<!-- 在引入css文件之后再引入js -->
<script src="https://unpkg.com/leaflet@1.9.3/dist/leaflet.js"></script>
...
<style>
/*地图显示需要DOM元素一个宽高 */
#map {
width: 100vw;
height: 100vh;
}
</style>
</head>
<body>
<!-- DOM挂载点 -->
<div id="map"></div>
<script>
const map = L.map('map', {
layers: [
L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution:
'© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
}),
],
center: [39.9, 116.4],
zoom: 8
})
</script>
</body>
② 结果

⑶ Mapbox
① 代码
<head>
...
<script src="https://api.mapbox.com/mapbox-gl-js/v3.5.1/mapbox-gl.js"></script>
<link href="https://api.mapbox.com/mapbox-gl-js/v3.5.1/mapbox-gl.css" rel="stylesheet"/>
...
<style>
#map {
width: 100vw;
height: 100vh;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
const map = new mapboxgl.Map({
//需要token
accessToken: 'pk.eyJ1IjoiemhvdWppbmJvIiwiYSI6ImNseThxbnZobDBqdXAycXBuOHA3MDkzeDQifQ.tsymc8MI26CSwETmtDl1OA',
//挂载点
container: 'map',
//图层数据管理放在style中
style: 'mapbox://styles/mapbox/streets-v12',
center: [116.4, 39.9],
zoom: 8,
})
</script>
</body>
② 结果

二 地图options成员
1. api对比
| OpenLayers | Leaflet | Mapbox | |
|---|---|---|---|
| 挂载点 | target string | HTMLElement | 地图初始化的第一个参数 string | HTMLElement | container string | HTMLElement |
| 图层数据 | layers Array | layers Array | style 满足style规范的JSON对象或者指向JSON对象的url |
| 视图中心点 | view.center Array[lng, lat] | center Array[lat, lng] | center Array[lng, lat] |
| 视图边界 | view.extent Array[minx, miny, maxx, maxy] | maxBounds LatLngBounds(sw, ne) | bounds LngLatBounds(sw, ne) |
| 缩放级别 | view.zoom number | zoom number | zoom number |
| 是否添加缩放控件 | ol.control.defaults({ zoom: false }).extend([ ]) | zoomControl boolean | |
| 是否滚动缩放 | scrollWheelZoom boolean | scrollZoom boolean | |
| 是否双击放大 | doubleClickZoom boolean | doubleClickZoom boolean | |
| 投影 | view.projection SRS 标识符 string 例如"EPSG:4326" | crs CRS | projection string | Object |
2. 代码与结果展示
⑴ OpenLayers
const map = new ol.Map({
target: "map",
Layers[
new ol.layer.Tile({
})
]
})