在网页中通过Leaflet API嵌入地图
本例将带领您了解Leaflet API,并在网页中快速插入来自Mapbox的一幅地图。
Step1 创建一个html页面,添加地图容器
从零开始,您可以:
- 先创建一个页面LeafletQuickStart.html
- 然后在页面中创建一个用于显示地图的容器:一个div,并设置id = "mapid"
- 定义样式,如高度设为600px
<!DOCTYPE html>
<html>
<head>
<title>Leaflet Quick Start Guide Example</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="mapid" style="width: 600px; height: 400px"></div>
</body>
</html>
Step2 引入在线JS库
在GettingStarted.html中的</head>标签前,加入引用的JS库与CSS文件,如下:
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css" />
<script src="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.js"></script>
其中,leaflet.js是Leaflet提供的在线JS库,可以很方便地使用地图。
Step3 在页面中插入Mapbox的在线地图瓦片
创建一个地图容器,并设置地图默认中心点为[51.505, -0.09],显示的地图级别为第13级。同时,setView默认开启了地图的漫游和缩放等鼠标交互。代码如下:
<script>
var mymap = L.map('mapid').setView([51.505, -0.09], 13);
</script>
有了地图容器以后,就可以为地图添加具体内容了,本例将添加来自Mapbox的地图瓦片。在添加瓦片前,您需要确保您具有可以访问Mapbox的账户,您的账户可以访问到地图瓦片,并为地图瓦片设置您的Access Token。
<script>
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpandmbXliNDBjZWd2M2x6bDk3c2ZtOTkifQ._QA7i5Mpkd_m30IGElHziw', {
maxZoom: 18,
attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
'<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
'Imagery © <a href="http://mapbox.com">Mapbox</a>',
id: 'mapbox.streets'
}).addTo(mymap);
</script>
在线演示与源码编辑
将LeafletQuickStart.html保存后,直接在浏览器中打开这个页面,您就可以浏览嵌入的地图。 您也可以通过在线体验的方式,直接在线编辑源码并实时查看演示效果。