Leaflet Quick Start Guide API

Keywords: Windows Javascript Mobile github

Tip: This tutorial is based on Leaflet's official tutorial, adding some comments and links to help readers learn Leaflet better. There are some inaccuracies or areas to be improved. You are welcome to comment.

Leaflet

an open-source JavaScript library for mobile-friendly interactive maps

Leaflet Quick Start Guide

This tutorial will give you a quick introduction to the basics of Leaflet, including setting up Leaflet maps, creating (lines, markers, prompt boxes) and handling events to give you a basic understanding of Leaflet.

Get ready

  • Introduce leaflet.js and leaflet.css files.
    leaflet.js,leaflet.css
  • Create a div container with a specific id.
    <div id="mapid"></div>
  • Define the height of the container.
    #mapid { height: 180px; }

Map setting

  • Using tile data of Mapbox Streets to create a map centered on Wuhan. First, we will initialize the map and set the view angle and zoom level of the map through the selected geographical coordinates.
//The latitude and longitude coordinates in leaflet are opposite to the actual coordinates, that is, the real geographic latitude and longitude coordinates are [114.398902, 30.518762]
var mymap = L.map('mapid').setView([30.518762, 114.398902], 13);

By default (no option configuration was passed in when we created the map instance), all mouse and touch interactions were invalid, with zoom (top left) and source (bottom right) controls on the interface.

  • Add tile layers to the map. Creating a tile layer usually requires setting the URL template, data source, and maximum zoom level for the tile image.
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
    attribution: 'Map data &copy; <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>',
    maxZoom: 18,
    id: 'mapbox.streets',
    accessToken: 'your.mapbox.access.token'
}).addTo(mymap);

It is worth noting that Leaflet does not force users to use tile maps from specific providers. Of course, when using tile maps from different providers, there will be some differences in grammar (for details, please refer to: Leaflet-providers For example, Mapbox, you have to register on Mapbox's official website, get ID and ACCESS_TOKEN before you can use it. Key acquisition address: mapbox key.

Markers,circles,polygons

In addition to tile layers, it is easy to add other things to the map, including marker s, polylines, polygons, circles and popups.

  • Add marker
var marker = L.marker([51.5, -0.09]).addTo(mymap); //You can add the appropriate options
  • Add circle
//Control the circle style by passing in the corresponding options
var circle = L.circle([51.508, -0.11], {
    color: 'red',         //Circle trajectory color, that is, the color of the outer border
    fillColor: '#f03',    //Fill in the color, the default value is the same as the color value
    fillOpacity: 0.5,     //Filling Transparency
    radius: 500           //circle radius, in meters
}).addTo(mymap);
  • Add polygon
//A plane is a two-dimensional array of coordinates.
var polygon = L.polygon([
    [51.509, -0.08],
    [51.503, -0.06],
    [51.51, -0.047]
]).addTo(mymap);

Use pop-up windows


When you want to attach some information to a specific object on a map, you usually need to use pop-up windows. Leaflet has a very convenient and fast method:

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

The bindPopup method attaches a pop-up window with specified HTML content to your tag so that a pop-up window appears when you click on the object. At the same time, the openPopup method is only applicable to marker.
Poups can be used as layers when you need more than just an additional pop-up object:

var popup = L.popup()
    .setLatLng([51.5, -0.09])
    .setContent("I am a standalone popup.")
    .openOn(mymap); //Using openOn instead of addTo, this method automatically closes the previous pop-up window when a new pop-up window is opened.

Handling events

_Events occurring on Leaflet, such as user clicking on markers or changing the map zoom size, the corresponding object will send an event that can be described by a function. It can respond to user interaction:

//Clicking anywhere on the map will bring up the coordinate information of the current location.
function onMapClick(e) {
    alert("You clicked the map at " + e.latlng);
}
mymap.on('click', onMapClick);

Each object has its own set of events. The first parameter of the listener function on() is an event object, which contains useful information about events that occur. For example, the map click event object (e in the example above) has a latlng attribute, which is the location at which the click occurs.
Let's improve our example by using pop-up windows instead of message dialogs:

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);

Posted by Ghulam Yaseen on Fri, 21 Dec 2018 06:54:05 -0800