Playing with Leaflet-Take you through the knowledge of Control

foreword

       As we all know, in the map application implemented by LeafLet.js, the control control can be used to switch between different basemaps. But if the default style is used for display, its effect is rather ugly. With the development of everyone's aesthetics, and with the need for more flexible custom functions, such as the need to integrate more beautiful basemaps, it usually needs to be expanded. So how to expand the control function of Leaflet to meet your actual needs? This article will introduce a Leaflet-based plug-in #Leaflet-IconLayers, through #Leaflet-IconLayers to realize the function of automatically switching layers, the article focuses on the Control component and how to expand these components, and gives example code.

1. What is Control?

        L.Control is a base class for implementing map controls in Leaflet. Responsible for handling positioning. All other controls are extended from this class.

1. Control option configuration

options type Defaults illustrate
position String 'topright' The position of the control (a corner of the map). Possible values ​​are  'topleft''topright''bottomleft' or 'bottomright'

2. Control method

method return value illustrate
getPosition() string Returns the position of the control.
setPostion<String postion> this Sets the position of the control.
getContainer() HTMLElement Returns the HTMLElement that contains this control.
addTo(<Map> map) this Adds the control to the given map.
remove() this Removes the control from the currently active map.

 3. Control default effect

         As can be seen from the above effects, its default layer controller is placed in the upper right corner, and the display effect is relatively general.

2. What is Leaflet-IconLayers?

1. Definition

       Leaflet-IconLayers is a switching controller with icons based on Leaflet. It needs to be used on Leaflet version 0.7.3 or higher, and the browser needs to be IE9+ or higher to access it normally. Those who are interested can download it by themselves: Leaflet-IconLayers . After using git to download the code, you can see the following project:

 2. Create a new html page

<!DOCTYPE html>
<html>
    <head>
	    <meta charset="utf-8" />
        <title>Leflet-IconLayers demo</title>
    <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" integrity="sha512-M2wvCLH6DSRazYeZRIm1JnYyh22purTM+FDB5CsyxtQJYeKq83arPe5wgbNmcFXGqiSH2XR8dT/fJISVA1r/zQ==" crossorigin=""/>
    <script src="https://unpkg.com/[email protected]/dist/leaflet.js" integrity="sha512-lInM/apFSqyy1o6s89K4iQUKg6ppXEgsVxT35HbzUupEVRh2Eu9Wdl4tHj7dZO0s1uvplcYGmt3498TtHq+log==" crossorigin=""></script>
        <script type="text/javascript" src="providers.js"></script>
        <script type="text/javascript" src="../src/iconLayers.js"></script>
        <link rel="stylesheet" href="../src/iconLayers.css">
        <style>
            body {
                margin: 0;
                padding: 0;
                width: 100%;
                height: 100%;
            }
            #map {
                position: absolute;
                top: 0;
                bottom: 0;
                left: 0;
                right: 0;
            }
        </style>
    </head>
    <body>
    </body>
</html>

       The iconLayers.js on the picture is the source code of the extension.

3. Basemap configuration

      The related basemap configuration is defined in providers.js. The detailed source code is as follows. For example, a local offline tile basemap is added at the front.

providers['local_tile'] = {
        title: 'local_tile',
        icon: 'icons/local_tile.png',
        layer: L.tileLayer('http://localhost:8086/data/basemap_water/{z}/{x}/{y}.png', {
			minZoom: 0,
            maxZoom: 16,
            attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">local_tile demo</a>'
        })
    };
(function(factory) {
    if (typeof module !== 'undefined' && module.exports) {
        module.exports = factory(require('leaflet'));
    } else {
        window.providers = factory(window.L);
    }
})(function(L) {
    var providers = {};

    providers['OpenStreetMap_Mapnik'] = {
        title: 'osm',
        icon: 'icons/openstreetmap_mapnik.png',
        layer: L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            maxZoom: 19,
            attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
        })
    };

    providers['OpenStreetMap_BlackAndWhite'] = {
        title: 'osm bw',
        icon: 'icons/openstreetmap_blackandwhite.png',
        layer: L.tileLayer('http://{s}.tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png', {
            maxZoom: 18,
            attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
        })
    };

    providers['OpenStreetMap_DE'] = {
        title: 'osm de',
        icon: 'icons/openstreetmap_de.png',
        layer: L.tileLayer('http://{s}.tile.openstreetmap.de/tiles/osmde/{z}/{x}/{y}.png', {
            maxZoom: 18,
            attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
        })
    }

    providers['Stamen_Toner'] = {
        title: 'toner',
        icon: 'icons/stamen_toner.png',
        layer: L.tileLayer('http://stamen-tiles-{s}.a.ssl.fastly.net/toner/{z}/{x}/{y}.png', {
            attribution: 'Map tiles by <a href="http://stamen.com">Stamen Design</a>, <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a> &mdash; Map data &copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
            subdomains: 'abcd',
            minZoom: 0,
            maxZoom: 20,
            ext: 'png'
        })
    };

    providers['Esri_OceanBasemap'] = {
        title: 'esri ocean',
        icon: 'icons/esri_oceanbasemap.png',
        layer: L.tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/Ocean_Basemap/MapServer/tile/{z}/{y}/{x}', {
            attribution: 'Tiles &copy; Esri &mdash; Sources: GEBCO, NOAA, CHS, OSU, UNH, CSUMB, National Geographic, DeLorme, NAVTEQ, and Esri',
            maxZoom: 13
        })
    };

    providers['HERE_normalDay'] = {
        title: 'normalday',
        icon: 'icons/here_normalday.png',
        layer: L.tileLayer('http://{s}.{base}.maps.cit.api.here.com/maptile/2.1/maptile/{mapID}/normal.day/{z}/{x}/{y}/256/png8?app_id={app_id}&app_code={app_code}', {
            attribution: 'Map &copy; 1987-2014 <a href="http://developer.here.com">HERE</a>',
            subdomains: '1234',
            mapID: 'newest',
            app_id: 'Y8m9dK2brESDPGJPdrvs',
            app_code: 'dq2MYIvjAotR8tHvY8Q_Dg',
            base: 'base',
            maxZoom: 20
        })
    };

    providers['HERE_normalDayGrey'] = {
        title: 'normalday grey',
        icon: 'icons/here_normaldaygrey.png',
        layer: L.tileLayer('http://{s}.{base}.maps.cit.api.here.com/maptile/2.1/maptile/{mapID}/normal.day.grey/{z}/{x}/{y}/256/png8?app_id={app_id}&app_code={app_code}', {
            attribution: 'Map &copy; 1987-2014 <a href="http://developer.here.com">HERE</a>',
            subdomains: '1234',
            mapID: 'newest',
            app_id: 'Y8m9dK2brESDPGJPdrvs',
            app_code: 'dq2MYIvjAotR8tHvY8Q_Dg',
            base: 'base',
            maxZoom: 20
        })
    };

    providers['HERE_satelliteDay'] = {
        title: 'satellite',
        icon: 'icons/here_satelliteday.png',
        layer: L.tileLayer('http://{s}.{base}.maps.cit.api.here.com/maptile/2.1/maptile/{mapID}/satellite.day/{z}/{x}/{y}/256/png8?app_id={app_id}&app_code={app_code}', {
            attribution: 'Map &copy; 1987-2014 <a href="http://developer.here.com">HERE</a>',
            subdomains: '1234',
            mapID: 'newest',
            app_id: 'Y8m9dK2brESDPGJPdrvs',
            app_code: 'dq2MYIvjAotR8tHvY8Q_Dg',
            base: 'aerial',
            maxZoom: 20
        })
    };

    providers['CartoDB_Positron'] = {
        title: 'positron',
        icon: 'icons/cartodb_positron.png',
        layer: L.tileLayer('http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', {
            attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> &copy; <a href="http://cartodb.com/attributions">CartoDB</a>',
            subdomains: 'abcd',
            maxZoom: 19
        })
    };
    return providers;
});

4. Add map object


var map = L.map('map').setView([29.052934, 104.0625], 5); 

var layers = [];
for (var providerId in providers) {
     layers.push(providers[providerId]);
}

layers.push({
      layer: {
           onAdd: function() {},
           onRemove: function() {}
       },
       title: 'empty'
})

var ctrl = L.control.iconLayers(layers).addTo(map);

5. The final effect

       Through the above steps, the custom extension function of control is basically completed. Let's take a look at the final effect. If you are not satisfied, you can also expand it according to the actual needs of your project.

 3. Summary

       The above is what I want to talk about today. This article mainly briefly introduces the definition and common methods of Control in Leaflet, and then focuses on Leaflet-IconLayers and its specific use. If you need to expand in your work, you may wish to use this method. In addition to this plugin, Leaflet also has many plugins to help achieve specific special effects. It is better to act than to be excited, so learn it quickly.

Guess you like

Origin blog.csdn.net/yelangkingwuzuhu/article/details/127721133