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/[email protected]/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/[email protected]/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的基礎內容,可以開始構建地圖應用了!別忘了還可以查看一下詳細的文檔及其他示例。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章