Leaflet官方教程 Leaflet Quick Start Guide 快速入门

This step-by-step guide will quickly get you started on Leaflet basics, including setting up a Leaflet map, working with markers, polylines and popups, and dealing with events.

这篇步进式教程会带你快速熟悉Leaflet,包括创建Leaflet地图,创建markers(点元素),折线及弹窗,以及处理事件。

 
See this example stand-alone.

Preparing your page

准备页面

Before writing any code for the map, you need to do the following preparation steps on your page:

在为地图编写代码之前,需要在页面中做一些准备工作。

  • Include Leaflet CSS file in the head section of your document:

  • 在页面的Head区域 引入Leaflet CSS文件:

     <link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.3/dist/leaflet.css"
       integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ=="
       crossorigin=""/>
    
  • Include Leaflet JavaScript file after Leaflet’s CSS:

  • 在CSS文件之后引入Leaflet的JavaScript文件:

     <!-- Make sure you put this AFTER Leaflet's CSS -->
     <script src="https://unpkg.com/leaflet@1.3.3/dist/leaflet.js"
       integrity="sha512-tAGcCfR4Sc5ZP5ZoVz0quoZDYX5aCtEm/eu1KhSLj2c9eFrylXZknQYmxUssFaVJKvvc0dJQixhGjG2yXWiV9Q=="
       crossorigin=""></script>
    
  • Put a div element with a certain id where you want your map to be:

  • 添加一个div,为div设置Id即地图的Id:

  •  <div id="mapid"></div>
    
  • Make sure the map container has a defined height, for example by setting it in CSS:

  • 对地图所在的div需要设置高度,例如可以在css中设置:

    #mapid { height: 180px; }

Now you’re ready to initialize the map and do some stuff with it.

现在可以初始化地图并做一些操作了。

Setting up the map

设置地图

 
See this example stand-alone.

Let’s create a map of the center of London with pretty Mapbox Streets tiles. First we’ll initialize the map and set its view to our chosen geographical coordinates and a zoom level:

我们目标是创建一个地图,添加漂亮的Mapbox 道路切片地图,中心定位到伦敦。首先我们初始化地图,设置其视野范围为选定的地理坐标范围,并设置指定的缩放级别。

var mymap = L.map('mapid').setView([51.505, -0.09], 13);

By default (as we didn’t pass any options when creating the map instance), all mouse and touch interactions on the map are enabled, and it has zoom and attribution controls.

默认情况下(如上面的代码我们创建地图时没有为其添加options属性),所有鼠标及触摸事件都是可用的,并且地图包含一个缩放组件(左上角)及版权组件(右下角)。

Note that setView call also returns the map object — most Leaflet methods act like this when they don’t return an explicit value, which allows convenient jQuery-like method chaining.

注意setView方法会返回map对象-大部分Leaflet的方法在没有明确的返回值都是这样的,这样我们就可以实现Jquery类似的链式调用。

Next we’ll add a tile layer to add to our map, in this case it’s a Mapbox Streets tile layer. Creating a tile layer usually involves setting the URL template for the tile images, the attribution text and the maximum zoom level of the layer. In this example we’ll use the mapbox.streets tiles from Mapbox’s “Classic maps” (in order to use tiles from Mapbox, you must also request an access token).

下面我们要为地图添加一个切片图层,在本里中为Mapbox发布的道路图层。创建一个切片图层通常包括设置其切片的URL模板,设置图层的版权信息,设置图层的最大缩放级别。在本例中,我们使用的mapbox.streets切片图层来自Mapbox的经典地图(要使用Mapbox的切片图层,还需要申请令牌)。

L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
    attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
    maxZoom: 18,
    id: 'mapbox.streets',
    accessToken: 'your.mapbox.access.token'
}).addTo(mymap);

Make sure all the code is called after the div and leaflet.js inclusion. That’s it! You have a working Leaflet map now.

所有的代码需要在div及leaflet.js引入之后调用。做完上述工作,我们就有了一个可以工作的Leaflet地图了。

It’s worth noting that Leaflet is provider-agnostic, meaning that it doesn’t enforce a particular choice of providers for tiles. You can try replacing mapbox.streets with mapbox.satellite, and see what happens. Also, Leaflet doesn’t even contain a single provider-specific line of code, so you’re free to use other providers if you need to (we’d suggest Mapbox though, it looks beautiful).

值的注意的是Leaflet并未绑定切片服务提供者,这意味着Leaflet不强制切片服务提供者。你可以试着将mapbox.streets替换为mapbox.satellite,查看效果。Leaflet甚至没有一行代码用于指定切片提供者。因此,我们可以自由使用需要的其他的地图提供商(不过我们还是建议使用Mapbox,因为它的确很好看)。

(意思应该是区别于ArcGIS for JavaScript,对于ArcGIS Server发布的地图都是一行代码搞定,对于其他的如mapbox的服务要使用ArcGIS for JavaScript加载就麻烦了。而Leaflet对这些服务提供商都一视同仁)

Whenever using anything based on OpenStreetMap, an attribution is obligatory as per the copyright notice. Most other tile providers (such as MapBoxStamen or Thunderforest) require an attribution as well. Make sure to give credit where credit is due.

在使用任意OpenStreetMap的内容时,属性组件的版权信息是必须的。其他的切片提供商(如MapBox,Stamen及Thundderforest)也需要提供版权信息。在需要声明版权信息时一定不要省略。

Markers, circles and polygons

Markers,圆及多边形

 
See this example stand-alone.

Besides tile layers, you can easily add other things to your map, including markers, polylines, polygons, circles, and popups. Let’s add a marker:

除了切片图层,还可以方便的添加很多其他地图内容,包括点标记(marker),折线,多边形,圆,弹窗。我们先添加一个点标记。

var marker = L.marker([51.5, -0.09]).addTo(mymap);

Adding a circle is the same (except for specifying the radius in meters as a second argument), but lets you control how it looks by passing options as the last argument when creating the object:

添加圆是类似的(除了在第二个参数中我们以米制单位指定了圆的半径),不同在于我们创建对象时将options作为最后一个参数来控制圆的外观:

var circle = L.circle([51.508, -0.11], {
    color: 'red',
    fillColor: '#f03',
    fillOpacity: 0.5,
    radius: 500
}).addTo(mymap);

Adding a polygon is as easy:

添加多边形也很简单:

var polygon = L.polygon([
    [51.509, -0.08],
    [51.503, -0.06],
    [51.51, -0.047]
]).addTo(mymap);

Working with popups

添加弹窗

 
See this example stand-alone.

Popups are usually used when you want to attach some information to a particular object on a map. Leaflet has a very handy shortcut for this:

弹窗通常用于为地图上的元素绑定一些信息。Leaflet可以很方便的实现这一功能。

marker.bindPopup("<b>Hello world!</b><br>I am a popup.").openPopup();
circle.bindPopup("I am a circle.");
polygon.bindPopup("I am a polygon.");

Try clicking on our objects. The bindPopup method attaches a popup with the specified HTML content to your marker so the popup appears when you click on the object, and the openPopup method (for markers only) immediately opens the attached popup.

现在点击一下之前添加的元素。bindPopup方法将一个包含指定HTML内容的弹窗与地图元素绑定,因此在点击对象时就会出现弹窗,openPopup方法(只有marker对象调用了该方法)会立即打开绑定的弹窗。

You can also use popups as layers (when you need something more than attaching a popup to an object):

也可以将弹窗作为图层使用(当需要展现信息而这些信息又不需要与地图元素绑定时):

var popup = L.popup()
    .setLatLng([51.5, -0.09])
    .setContent("I am a standalone popup.")
    .openOn(mymap);

Here we use openOn instead of addTo because it handles automatic closing of a previously opened popup when opening a new one which is good for usability.

这里我们使用openOn 而非addTo,openOn在打开一个新弹窗时会自动的关闭之前打开的弹窗,这可以提高可用性。

Dealing with events

处理事件

Every time something happens in Leaflet, e.g. user clicks on a marker or map zoom changes, the corresponding object sends an event which you can subscribe to with a function. It allows you to react to user interaction:

每当Leaflet中发生某些事情时,例如,用户点击了一个点标记或者地图缩放级别有变化,对应的对象就会发出事件,我们可以订阅这些事件,添加处理函数。从而实现用户交互响应。

function onMapClick(e) {
    alert("You clicked the map at " + e.latlng);
}

mymap.on('click', onMapClick);

Each object has its own set of events — see documentation for details. The first argument of the listener function is an event object — it contains useful information about the event that happened. For example, map click event object (e in the example above) has latlng property which is a location at which the click occured.

每个对象都有其特定的事件列表-可以查看API文档了解详细内容。事件监听函数的第一个参数是一个event对象-它包含事件发生时的一些有用信息。例如,地图点击事件对象(上面代码中的e)包含的latlng(坐标)属性为点击位置的坐标。

Let’s improve our example by using a popup instead of an alert:

我们alert替换为popup来改进我们的代码。

var popup = L.popup();

function onMapClick(e) {
    popup
        .setLatLng(e.latlng)
        .setContent("You clicked the map at " + e.latlng.toString())
        .openOn(mymap);
}

mymap.on('click', onMapClick);

Try clicking on the map and you will see the coordinates in a popup. View the full example →

尝试点击地图,你会看到弹窗中展示了点击位置的坐标。点击超链接可以查看完整示例。

Now you’ve learned Leaflet basics and can start building map apps straight away! Don’t forget to take a look at the detailed documentation or other examples.

现在我们已经学习了Leaflet的基础内容,可以开始构建地图应用了!别忘了还可以查看一下详细的文档及其他示例。

转载自:https://blog.csdn.net/pyluyuan/article/details/81589874

You may also like...