Leaflet_创建地图(官网示例,可以直接运行)(2017-10-20)

官网:http://leafletjs.com/examples.html

快速启动指南

http://leafletjs.com/examples/quick-start/example.html

一个简单的一步一步的引导,很快就会让你开始用传单的基础知识,包括建立一个单张地图(Mapbox瓷砖)在您的网页上,与标记、折线和弹出窗口,和事件处理。

<!DOCTYPE html>
<html>

    <head>
        <title>Leaflet1</title>
        <meta charset="utf-8">
        <link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css">
        <script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet.js"></script>
        <style TYPE="text/css">
            body {
                margin: 0px;
                padding: 0px;
            }
            /**
             * 单独设置mapid为100%不显示,可能float坍塌
             */
            
            html,
            body,
            #mapDiv {
                height: 100%;
                width: 100%;
            }
        </style>
    </head>

    <body>
        <div id="mapDiv">
        </div>
    </body>
    <script>
        //地图地址
        var url = 'https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw';
        var attr = ' Map data &copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, &copy; <a href="http://cartodb.com/attributions">CartoDB</a>';

        var leafletMap = L.map('mapDiv').setView([51.505, -0.09], 13);
        //图层
        L.tileLayer(url, {
            maxZoom: 18,
            attribution: attr,
            id: 'mapbox.streets'
        }).addTo(leafletMap);
        //标记点
        L.marker([51.5, -0.09]).addTo(leafletMap)
            .bindPopup("<b>Hello world!</b><br />I am a popup.").openPopup();
        //
        L.circle([51.508, -0.11], 500, {
            color: 'red',
            fillColor: '#f03',
            fillOpacity: 0.5
        }).addTo(leafletMap).bindPopup("I am a circle.");
        //多边形
        L.polygon([
            [51.509, -0.08],
            [51.503, -0.06],
            [51.51, -0.047]
        ]).addTo(leafletMap).bindPopup("I am a polygon.");
        //弹出面板
        var popup = L.popup();

        function onMapClick(e) {
            popup
                .setLatLng(e.latlng)
                .setContent("You clicked the map at " + e.latlng.toString())
                .openOn(leafletMap);
        }
        //添加click时间
        leafletMap.on('click', onMapClick);
    </script>

</html>
View Code

移动端

http://leafletjs.com/examples/mobile/example.html

在本教程中,您将学习如何创建一个全屏地图调整为移动设备如iPhone,iPad或Android手机,以及如何轻松地检测并使用当前用户的位置。

<!DOCTYPE html>
<html>

    <head>
        <title>Leaflet2</title>
        <meta charset="utf-8">
        <link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css">
        <script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet.js"></script>
        <style TYPE="text/css">
            body {
                margin: 0px;
                padding: 0px;
            }
            /**
             * 单独设置mapid为100%不显示,可能float坍塌
             */
            
            html,
            body,
            #mapDiv {
                height: 100%;
                width: 100%;
            }
        </style>
    </head>

    <body>
        <div id="mapDiv">
        </div>
    </body>
    <script>
        //地图地址
        var url = 'https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw';
        var attr = ' Map data &copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, &copy; <a href="http://cartodb.com/attributions">CartoDB</a>';

        var leafletMap = L.map('mapDiv').fitWorld();

        L.tileLayer(url, {
            maxZoom: 18,
            attribution: attr,
            id: 'mapbox.streets'
        }).addTo(leafletMap);

        function onLocationFound(e) {
            var radius = e.accuracy / 2; //精度

            L.marker(e.latlng).addTo(leafletMap)
                .bindPopup("You are within " + radius + " meters from this point").openPopup();

            L.circle(e.latlng, radius).addTo(leafletMap);
        }

        function onLocationError(e) {
            alert(e.message);
        }

        //注册事件
        //locationerror     ErrorEvent    开枪时,地理位置(使用locate失败的方法)
        //locationfound     LocationEvent    开枪时,地理位置(使用locate方法)去成功
        leafletMap.on('locationfound', onLocationFound);
        leafletMap.on('locationerror', onLocationError);

        //地理定位的方法
        //尝试使用地理定位API定位用户,射击locationfound在成功的一个位置或数据事件locationerror事件的失败,和可选的设置地图视图检测精度相对于用户的位置(或世界观如果定位失败)
        leafletMap.locate({
            setView: true, //如果true自动设置图来看,相对于用户的位置检测精度,或世界观如果定位失败。
            maxZoom: 16 //当使用自动设置视图的最大变焦setView选项
        });
    </script>

</html>
View Code

自定义图标的标记 

http://leafletjs.com/examples/custom-icons/example.html

在这个漂亮的教程,你将学习如何轻松地定义自己使用的标记,你把地图上的图标。

<!DOCTYPE html>
<html>

    <head>
        <title>Leaflet3</title>
        <meta charset="utf-8">
        <link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css">
        <script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet.js"></script>
        <style TYPE="text/css">
            body {
                margin: 0px;
                padding: 0px;
            }
            /**
             * 单独设置mapid为100%不显示,可能float坍塌
             */
            
            html,
            body,
            #mapDiv {
                height: 100%;
                width: 100%;
            }
        </style>
    </head>

    <body>
        <div id="mapDiv">
        </div>
    </body>
    <script>
        //地图地址
        var url = 'https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw';
        var attr = '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors';

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

        L.tileLayer(url, {
            attribution: attr,
            id: 'mapbox.streets'
        }).addTo(leafletMap);
        
        
        //图标
        var shadowUrl = "http://leafletjs.com/examples/custom-icons/leaf-shadow.png";
        var orangeUrl = "http://leafletjs.com/examples/custom-icons/leaf-orange.png";
        var redUrl = "http://leafletjs.com/examples/custom-icons/leaf-red.png";
        var greenUrl = "http://leafletjs.com/examples/custom-icons/leaf-green.png";

        var LeafIcon = L.Icon.extend({
            options: {
                shadowUrl: shadowUrl,
                iconSize: [38, 95],
                shadowSize: [50, 64],
                iconAnchor: [22, 94],
                shadowAnchor: [4, 62],
                popupAnchor: [-3, -76]
            }
        });

        var greenIcon = new LeafIcon({
            iconUrl: greenUrl
        });
        var redIcon = new LeafIcon({
            iconUrl: redUrl
        });
        var orangeIcon = new LeafIcon({
            iconUrl: orangeUrl
        });

        L.marker([51.5, -0.09], {
            icon: greenIcon
        }).bindPopup("I am a green leaf.").addTo(leafletMap);
        L.marker([51.495, -0.083], {
            icon: redIcon
        }).bindPopup("I am a red leaf.").addTo(leafletMap);
        L.marker([51.49, -0.1], {
            icon: orangeIcon
        }).bindPopup("I am an orange leaf.").addTo(leafletMap);
    </script>

</html>
View Code

用GeoJSON

http://leafletjs.com/examples/geojson/example.html

在本教程中,您将学习如何创建和使用地图矢量产生互动GeoJSON目标

<!DOCTYPE html>
<html>

    <head>
        <title>Leaflet4</title>
        <meta charset="utf-8">
        <link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css">
        <script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet.js"></script>
        <style TYPE="text/css">
            body {
                margin: 0px;
                padding: 0px;
            }
            /**
             * 单独设置mapid为100%不显示,可能float坍塌
             */
            
            html,
            body,
            #mapDiv {
                height: 100%;
                width: 100%;
            }
        </style>
    </head>

    <body>
        <div id="mapDiv">
        </div>
    </body>

    <script type="text/javascript" src="http://leafletjs.com/examples/geojson/sample-geojson.js"></script>

    <script>
        //地图地址
        var url = 'https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw';
        var attr = ' Map data &copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, &copy; <a href="http://cartodb.com/attributions">CartoDB</a>';

        var leafletMap = L.map('mapDiv').setView([39.74739, -105], 13);

        L.tileLayer(url, {
            maxZoom: 18,
            attribution: attr,
            id: 'mapbox.light'
        }).addTo(leafletMap);

        //注册图标
        var iconUrl = "http://leafletjs.com/examples/geojson/baseball-marker.png";
        var baseballIcon = L.icon({
            iconUrl: iconUrl,
            iconSize: [32, 37],
            iconAnchor: [16, 37],
            popupAnchor: [0, -28]
        });

        //例1
        //geoJson 地址:http://geojson.org/geojson-spec.html
        //Feature类型geoJson对象
        //必须有properties对象
        //geometry对象,是几何对象
        var geojsonFeature = {
            "type": "Feature",
            "properties": {
                "name": "Coors Field",
                "amenity": "Baseball Stadium",
                "popupContent": "This is where the Rockies play!"
            },
            "geometry": {
                "type": "Point",
                "coordinates": [-104.94404, 39.75621]
            }
        };
        //加入到map中
        L.geoJSON(geojsonFeature).addTo(leafletMap);

        //例2
        //LineString类型geoJson对象
        var myLines = [{
            "type": "LineString",
            "coordinates": [
                [-104.7, 39.6],
                [-104.8, 39.7],
                [-104.9, 39.8]
            ]
        }, {
            "type": "LineString",
            "coordinates": [
                [-104.8, 39.6],
                [-104.9, 39.7],
                [-105.0, 39.8]
            ]
        }];
        var myLayer = L.geoJSON().addTo(leafletMap);
        myLayer.addData(myLines);

        //例3 style
        //LineString类型geoJson对象
        var myLines = [{
            "type": "LineString",
            "coordinates": [
                [-104.9, 39.6],
                [-105.0, 39.7],
                [-105.1, 39.8]
            ]
        }, {
            "type": "LineString",
            "coordinates": [
                [-105.0, 39.6],
                [-105.1, 39.7],
                [-105.2, 39.8]
            ]
        }];
        //style风格
        var myStyle = {
            "color": "#ff7800",
            "weight": 5,
            "opacity": 0.65
        };

        L.geoJSON(myLines, {
            style: myStyle
        }).addTo(leafletMap);

        //例4 style根据属性改变
        //共和党,民主党区域
        //Feature类型geoJson对象,里边两个多边形。
        var states = [{
            "type": "Feature",
            "properties": {
                "party": "Republican" //党:共和党
            },
            "geometry": {
                "type": "Polygon",
                "coordinates": [
                    [
                        [-104.85, 39.59],
                        [-104.72, 39.58],
                        [-104.72, 39.79],
                        [-104.83, 39.79],
                        [-104.95, 39.59]
                    ]
                ]
            }
        }, {
            "type": "Feature",
            "properties": {
                "party": "Democrat" //民主党
            },
            "geometry": {
                "type": "Polygon",
                "coordinates": [
                    [
                        [-104.96, 40.00],
                        [-104.76, 39.99],
                        [-104.73, 39.49],
                        [-104.96, 39.49],
                        [-104.96, 40.00]
                    ]
                ]
            }
        }];
        //style风格 根据feature.properties.party属性来确定颜色
        L.geoJSON(states, {
            style: function(feature) {
                switch(feature.properties.party) {
                    case 'Republican':
                        return {
                            color: "#ff0000"
                        };
                    case 'Democrat':
                        return {
                            color: "#0000ff"
                        };
                }
            }
        }).addTo(leafletMap);

        //加载geoJson数据(campus:(大学)校园,BicycleRental :自行车租赁处 两个多边形,以及n个点)
        //设置样式风格,onEachFeature事件效果以及pointToLayer点渲染并加入到map中
        L.geoJSON([bicycleRental, campus], {
            //a && b : 将a, b转换为Boolean类型, 再执行逻辑与, true返回b, false返回a
            //a || b : 将a, b转换为Boolean类型, 再执行逻辑或, true返回a, false返回b
            //风格:获取feature对象的properties变量的style属性
            style: function(feature) {
                return feature.properties && feature.properties.style;
            },
            onEachFeature: onEachFeature,
            pointToLayer: pointToLayerByCircleMarker
        }).addTo(leafletMap);

        //加载geoJson数据( 免费公交车: 免费公交车,3条线)
        //设置onEachFeature事件效果以及过滤器并加入到map中
        L.geoJSON(freeBus, {
            filter: filter,
            onEachFeature: onEachFeature
        }).addTo(leafletMap);

        //加载geoJson数据(一个点) 加了一个图标呢
        //设置onEachFeature事件效果以及pointToLayer点渲染并加入到map中
        var coorsLayer = L.geoJSON(coorsField, {
            pointToLayer: pointToLayerByMarker,
            onEachFeature: onEachFeature
        }).addTo(leafletMap);

        //pointToLayer 对Point类型对象的每个坐标设置标记选项
        function pointToLayerByMarker(feature, latlng) {
            return L.marker(latlng, {
                icon: baseballIcon
            });
        }

        //pointToLayer 对Point类型对象的每个坐标设置标记选项
        function pointToLayerByCircleMarker(feature, latlng) {
            return L.circleMarker(latlng, circleMarkerOptions); //对坐标加载标记选项配置
        }

        //geojson标记选项
        var circleMarkerOptions = {
            radius: 10, //半径像素
            color: "#00ff00", //边框颜色
            weight: 10, //边框宽度像素
            opacity: 0.5, //边框不透明度
            fillColor: "#ff7800", //填充颜色
            fillOpacity: 0.8 //填充不透明度
        };

        //每个Feature对象,附加事件和弹出功能。默认是与新创建的图层做什么:
        function onEachFeature(feature, layer) {
            var popupContent = "<p>I started out as a GeoJSON " +
                feature.geometry.type + ", but now I'm a Leaflet vector!</p>";

            if(feature.properties && feature.properties.popupContent) {
                popupContent += feature.properties.popupContent;
            }

            layer.bindPopup(popupContent);
        }

        //过滤器 
        //顾虑掉建造中的,施工中的
        function filter(feature, layer) {
            if(feature.properties) {
                // If the property "underConstruction" exists and is true, return false (don't render features under construction)
                return feature.properties.underConstruction !== undefined ? !feature.properties.underConstruction : true;
            }
            return false;
        };
    </script>

</html>
View Code

交互图

 http://leafletjs.com/examples/choropleth/example.html

创造一个丰富多彩的互动为例分布图我们国家的人口密度和一些自定义控件GeoJSON。新闻网站会将这份爱。

<!DOCTYPE html>
<html>

    <head>
        <title>Leaflet5</title>
        <meta charset="utf-8">
        <link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css">
        <script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet.js"></script>
        <style TYPE="text/css">
            body {
                margin: 0px;
                padding: 0px;
            }
            /**
             * 单独设置mapid为100%不显示,可能float坍塌
             */
            
            html,
            body,
            #mapDiv {
                height: 100%;
                width: 100%;
            }
        </style>
    </head>

    <body>
        <div id="mapDiv">
        </div>
    </body>
    <!--
        描述:美国政府
      -->
    <script type="text/javascript" src="http://leafletjs.com/examples/choropleth/us-states.js"></script>

    <script>
        //地图地址
        var url = 'https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw';
        var attr = ' Map data &copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, &copy; <a href="http://cartodb.com/attributions">CartoDB</a>';

        var leafletMap = L.map('mapDiv').setView([37.8, -96], 4);

        L.tileLayer(url, {
            maxZoom: 18,
            attribution: attr,
            id: 'mapbox.light'
        }).addTo(leafletMap);

        //将geoJson数据加入到map中
        geojson = L.geoJson(statesData, {
            style: style,
            onEachFeature: onEachFeature
        }).addTo(leafletMap);

        //初始化控件info
        var info = L.control();

        //要返回的控制容器的DOM元素和添加有关地图的事件侦听器。
        info.onAdd = function(leafletMap) {
            //添加一个class='info'的div
            this._div = L.DomUtil.create('div', 'info');
            this.update(); //初始化显示
            return this._div;
        };

        info.update = function(props) {
            //如果props存在则插入州名以及密度,否则显示默认
            this._div.innerHTML = '<h4>美国人口密度</h4>' + (props ?
                '<b>' + props.name + '</b><br />' + props.density + ' 人 / 公里<sup>2</sup>' :
                '');
        };
        //添加进地图
        info.addTo(leafletMap);

        //初始化控件info
        var legend = L.control({
            position: 'bottomright' //位置右下角
        });

        //要返回的控制容器的DOM元素和添加有关地图的事件侦听器。
        legend.onAdd = function(leafletMap) {
            //添加一个class='info legend'的div
            var div = L.DomUtil.create('div', 'info legend');
            var grades = [0, 10, 20, 50, 100, 200, 500, 1000]; //等级
            var labels = []; //标签 数组
            var from; //等级A
            var to; //等级B

            for(var i = 0; i < grades.length; i++) {
                from = grades[i];
                to = grades[i + 1];

                //显示从A-B如果没有B则显示+号 &ndash 为-
                labels.push(
                    '<i style="background:' + getColor(from + 1) + '">' +
                    from + (to ? '&ndash;' + to : '+') + '</i> ');
            }

            div.innerHTML = labels.join('<br>');
            return div;
        };
        //添加进地图
        legend.addTo(leafletMap);
        //追加右下角属性控件
        leafletMap.attributionControl.addAttribution('人口数据&copy; <a href="http://census.gov/">美国人口普查局</a>');

        //每个Feature对象,附加事件和弹出功能。默认是与新创建的图层做什么:
        function onEachFeature(feature, layer) {
            layer.on({
                mouseover: highlightFeature,
                mouseout: resetHighlight,
                click: zoomToFeature
            });
        }

        //根据d大小返回相应颜色
        function getColor(d) {
            return d > 1000 ? '#800026' :
                d > 500 ? '#BD0026' :
                d > 200 ? '#E31A1C' :
                d > 100 ? '#FC4E2A' :
                d > 50 ? '#FD8D3C' :
                d > 20 ? '#FEB24C' :
                d > 10 ? '#FED976' :
                '#FFEDA0';
        }
        //根据feature对象属性density提供对应的风格样式
        function style(feature) {
            return {
                fillColor: getColor(feature.properties.density),
                weight: 2,
                opacity: 1,
                color: 'white',
                dashArray: '3',
                fillOpacity: 0.7
            };
        }

        //设置Feature高亮
        //通过e.target获得layer,设置灰色高亮
        function highlightFeature(e) {
            var layer = e.target; //触发事件的对象

            layer.setStyle({
                weight: 5,
                color: '#666', //灰色
                dashArray: '', //
                fillOpacity: 0.7
            });

            if(!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) {
                layer.bringToFront(); //将弹出在其他弹出窗口前(在同一地图窗格)。
            }
            //调用控件info的修改方法
            info.update(layer.feature.properties);
        }

        //设置重置高亮
        function resetHighlight(e) {
            geojson.resetStyle(e.target);
            //调用控件info的修改方法
            info.update();
        }

        //设置Feature缩放 ,到点击的对象合适的大小    
        function zoomToFeature(e) {
            //将地图视图尽可能大地设定在给定的地理边界内.
            leafletMap.fitBounds(e.target.getBounds());
        }
    </script>

</html>
View Code

图层组和图层控制

http://leafletjs.com/examples/layers-control/

本教程将向你展示如何组成一个几层,以及如何使用图层控制允许用户方便地切换不同的层在你的地图上。

<!DOCTYPE html>
<html>

    <head>
        <title>Leaflet6</title>
        <meta charset="utf-8">
        <link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css">
        <script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet.js"></script>
        <style TYPE="text/css">
            body {
                margin: 0px;
                padding: 0px;
            }
            /**
             * 单独设置mapid为100%不显示,可能float坍塌
             */
            
            html,
            body,
            #mapDiv {
                height: 100%;
                width: 100%;
            }
        </style>
    </head>

    <body>
        <div id="mapDiv">
        </div>
    </body>

    <script>
        //地图地址
        var url = 'https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw';
        var attr = ' Map data &copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, &copy; <a href="http://cartodb.com/attributions">CartoDB</a>';

        //新建一个层组cities
        var cities = L.layerGroup();
        //将maker添加到图层组cities中
        L.marker([39.61, -105.02]).bindPopup('This is Littleton, CO.').addTo(cities);
        L.marker([39.74, -104.99]).bindPopup('This is Denver, CO.').addTo(cities);
        
        //新建一个层组cities2
        var cities2 = L.layerGroup();
        L.marker([39.73, -104.8]).bindPopup('This is Aurora, CO.').addTo(cities2);
        L.marker([39.77, -105.23]).bindPopup('This is Golden, CO.').addTo(cities2);

        //新建grayscale图层
        var grayscale = L.tileLayer(url, {
            id: 'mapbox.light',
            attribution: url
        });

        //新建streets图层
        var streets = L.tileLayer(url, {
            id: 'mapbox.streets',
            attribution: url
        });

        //初始化map,并设置基本图层为grayscale,覆盖图层cities
        var leafletMap = L.map('mapDiv', {
            center: [39.73, -104.99],
            zoom: 10,
            layers: [grayscale, cities] //默认图层
        });

        //grayscale 与 streets 互斥
        var baseLayers = {
            "Grayscale": grayscale,
            "Streets": streets
        };

        //overlay—在base layer之上放置的其他东西。
        var overlays = {
            "Cities": cities,
            "Cities2": cities2
        };

        //baselayers—互斥的图层(在地图上同一时间只能有一个图层可见)
        //overlays—在base layer之上放置的其他东西。
        //添加进地图
        L.control.layers(baseLayers, overlays).addTo(leafletMap);
    </script>

</html>
View Code

缩放级别

http://leafletjs.com/examples/zoom-levels/

单张作品纬度经度和“放大”的水平

较低的缩放级别意味着地图显示了整个大陆,而高zoomlevels意味着地图可以显示一个城市的细节。

<!DOCTYPE html>
<html>

    <head>
        <title>Leaflet7</title>
        <meta charset="utf-8">
        <link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css">
        <script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet.js"></script>
        <style TYPE="text/css">
            body {
                margin: 0px;
                padding: 0px;
            }
            /**
             * 单独设置mapid为100%不显示,可能float坍塌
             */
            
            html,
            body,
            #mapDiv {
                height: 100%;
                width: 100%;
            }
        </style>
    </head>

    <body>
        <div id="mapDiv">
        </div>
    </body>

    <script>
        //地图地址
        var url = 'http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png';
        var attr = ' Map data &copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, &copy; <a href="http://cartodb.com/attributions">CartoDB</a>';

        //初始化地图
        var leafletMap = L.map('mapDiv', {
            minZoom: 0, //地图的最小视图。可以重写地图图层的minZoom.
            maxZoom: 18, //地图的最大视图。可以重写地图图层的maxZoom.
            zoomSnap: 0, //缩放粒度
            zoomDelta: 0.25, //变焦增量+-滚轮一下缩放多少
            dragging: true, //可拖动
            opacity: 0.1,       //图层的不透明度
            maxBounds: [        //地图的东西南北最大边界,
                                //在缩放级别合适的情况下,地图只会展示在当前的区域内
                //south west
                [34.6, 113.4],
                //north east
                [34.9, 113.98]
            ]
            
        });

        //图层positron
        var positron = L.tileLayer(url, {
            attribution: attr
        }).addTo(leafletMap);
        
        //缩放等级显示器,右上角
        var ZoomViewer = L.Control.extend({
            //onadd方法 要返回的控制容器的DOM元素和添加有关地图的事件侦听器。
            onAdd: function() {
                var container = L.DomUtil.create('div'); //容器div
                container.style.width = '200px';
                container.style.background = 'rgba(255,255,255,0.5)';
                container.style.textAlign = 'left';
                var gauge = L.DomUtil.create('div'); //计量器div
                leafletMap.on('zoomstart zoom zoomend', function(ev) {
                    gauge.innerHTML = '缩放等级: ' + leafletMap.getZoom();
                })
                container.appendChild(gauge); //计量器放入容器中

                return container;
            }
        });

        (new ZoomViewer).addTo(leafletMap);


        //设置比例尺,左下角
        L.control.scale({
            maxWidth: 100 //不懂
        }).addTo(leafletMap);

        /**
        //8s执行一次zoomCycle(缩放循环)
        function zoomCycle() {
            leafletMap.setZoom(0);
            timeouts = [];
            timeouts.push(setTimeout(function(){ leafletMap.setZoom(0.25); },  1000));
            timeouts.push(setTimeout(function(){ leafletMap.setZoom(0.50); },  2000));
            timeouts.push(setTimeout(function(){ leafletMap.setZoom(0.75); },  3000));
            timeouts.push(setTimeout(function(){ leafletMap.setZoom(1);    },  4000));
            timeouts.push(setTimeout(function(){ leafletMap.setZoom(0.75); },  5000));
            timeouts.push(setTimeout(function(){ leafletMap.setZoom(0.50); },  6000));
            timeouts.push(setTimeout(function(){ leafletMap.setZoom(0.25); },  7000));
        }
        zoomCycle();
        var zoomingInterval = setInterval(zoomCycle, 8000);
        */
        /**
        //使用SetInterval和设定延时函数setTimeout 很类似。setTimeout 运用在延迟一段时间,再进行某项操作。
        //setTimeout("function",time) 设置一个超时对象 setInterval("function",time) 设置一个超时对象
        //SetInterval为自动重复,setTimeout不会重复。
        //设置时间间隔函数,4s调用一次
        setInterval(function() {

            leafletMap.setZoom(0);

            setTimeout(function() {
                leafletMap.setZoom(1);
            }, 2000);

        }, 4000);
        */
        //地图的中心点的对象
        var mapcenter = new L.latLng(21.5,67.89);
        //地图设置中心店坐标,以及缩放级别
        leafletMap.setView(mapcenter, 12);
    </script>

</html>
View Code

非地理图

http://leafletjs.com/examples/crs-simple/crs-simple.html

入门L.CRS.Simple,如何使地图没有概念的“纬度”、“经度”。

<!DOCTYPE html>
<html>

    <head>
        <title>Leaflet8</title>
        <meta charset="utf-8">
        <link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css">
        <script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet.js"></script>
        <style TYPE="text/css">
            body {
                margin: 0px;
                padding: 0px;
            }
            /**
             * 单独设置mapid为100%不显示,可能float坍塌
             */
            
            html,
            body,
            #mapDiv {
                height: 100%;
                width: 100%;
            }
        </style>
    </head>

    <body>
        <div id="mapDiv">
        </div>
    </body>

    <script>
        var leafletMap = L.map('mapDiv', {
            crs: L.CRS.Simple, //坐标参考系统Simple
            minZoom: -3 //设置为可缩放级别的下限(可以放得更大)
        });

        //sol在坐标[145,175]而不是[ 175,145 ],和同样的情况发生在地图中心。
        //坐标CRS.Simple采取的形式【Y,X ]而不是[x, y]以同样的方式使用,单张【LAT,LNG ]而不是[lng, lat]
        //坐标转换
        var yx = L.latLng;

        var xy = function(x, y) {
            //当调用此函数传入的第一个参数是数组xy([x, y]);,则分解
            if(L.Util.isArray(x)) {
                return yx(x[1], x[0]);
            }
            //当调用此函数传入的是xy(x, y);形式
            return yx(y, x);
        };

        var imageUrl = "http://leafletjs.com/examples/crs-simple/uqm_map_full.png";
        var imageBounds = [xy(-25, -26.5), xy(1023, 1021.5)];
        //用于加载和显示一个图像在地图上的特定范围。
        var image = L.imageOverlay(imageUrl, imageBounds).addTo(leafletMap);

        //设置一个坐标
        var sol = xy(175.2, 145.0);
        var mizar = xy(41.6, 130.1);
        var kruegerZ = xy(13.4, 56.5);
        var deneb = xy(218.7, 8.3);

        //加marker标识
        L.marker(sol).addTo(leafletMap).bindPopup('Sol');
        L.marker(mizar).addTo(leafletMap).bindPopup('Mizar');
        L.marker(kruegerZ).addTo(leafletMap).bindPopup('Krueger-Z');
        L.marker(deneb).addTo(leafletMap).bindPopup('Deneb');

        //多线
        var travel = L.polyline([sol, deneb]).addTo(leafletMap);
        //地图设置中心店坐标,以及缩放级别
        leafletMap.setView(xy(120, 70), 1);

        //设置一个地图视图包含了最大变焦水平可能的地理界限。
        //leafletMap.fitBounds(imageBounds);
    </script>

</html>
View Code

WMS

http://leafletjs.com/examples/wms/wms.html

如何从专业的GIS软件WMS服务整合。

<!DOCTYPE html>
<html>

    <head>
        <title>Leaflet9</title>
        <meta charset="utf-8">
        <link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css">
        <script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet.js"></script>
        <style TYPE="text/css">
            body {
                margin: 0px;
                padding: 0px;
            }
            /**
             * 单独设置mapid为100%不显示,可能float坍塌
             */
            
            html,
            body,
            #mapDiv {
                height: 100%;
                width: 100%;
            }
        </style>
    </head>

    <body>
        <div id="mapDiv">
        </div>
    </body>

    <script>
        //地图地址
        var wmsUrl = 'https://demo.boundlessgeo.com/geoserver/ows?';

        var leafletMap = L.map('mapDiv', {
            crs: L.CRS.EPSG4326, //坐标系统:CRS:3857,CRS:33954和CRS:4326,只要使用正确的CRS初始化地图时,任何WMS层会使用它:
            center: [36.070036, 103.816375], //初始化地图的地理中心.
            zoom: 5 //初始化地图的缩放.
        });
        /**
        var wmsLayer = L.tileLayer.wms(wmsUrl, {
            layers: 'ne:ne'
        }).addTo(leafletMap);
        */
        /*
        var wmsLayer = L.tileLayer.wms(wmsUrl, {
            layers: 'nasa:bluemarble'
        }).addTo(leafletMap);
        */

        //图层组   
        //每个L.tileLayer.wms返回值都是layer
        //ne:ne_10m_admin_0_countries国家名
        //ne:ne_10m_admin_0_boundary_lines_land 边界线
        var basemaps = {
            Countries: L.tileLayer.wms(wmsUrl, {
                layers: 'ne:ne_10m_admin_0_countries'
            }),

            Boundaries: L.tileLayer.wms(wmsUrl, {
                layers: 'ne:ne_10m_admin_0_boundary_lines_land'
            }),
            //因为key-value形式不能有空格所以用单引号包起来
            'Countries, then boundaries': L.tileLayer.wms(wmsUrl, {
                layers: 'ne:ne_10m_admin_0_countries,ne:ne_10m_admin_0_boundary_lines_land'
            }),

            'Boundaries, then countries': L.tileLayer.wms(wmsUrl, {
                layers: 'ne:ne_10m_admin_0_boundary_lines_land,ne:ne_10m_admin_0_countries'
            })
        };

        L.control.layers(basemaps).addTo(leafletMap);
        //初始化map
        basemaps.Countries.addTo(leafletMap);
    </script>

</html>
View Code

地图上的工作

http://leafletjs.com/examples/map-panes/

的默认的地图上工作上的瓷砖显示重叠,以及如何重写。

<!DOCTYPE html>
<html>

    <head>
        <title>Leaflet10</title>
        <meta charset="utf-8">
        <link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css">
        <script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet.js"></script>
        <style TYPE="text/css">
            body {
                margin: 0px;
                padding: 0px;
            }
            /**
             * 单独设置mapid为100%不显示,可能float坍塌
             */
            
            html,
            body,
            #mapDiv {
                height: 100%;
                width: 100%;
            }
        </style>
    </head>

    <body>
        <div id="mapDiv">
        </div>
    </body>
    <script type="text/javascript" src="http://leafletjs.com/examples/map-panes/eu-countries.js"></script>
    <script>
        //地图地址
        var nolabelsUrl = 'http://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}.png';
        var lablesUrl = 'http://{s}.basemaps.cartocdn.com/light_only_labels/{z}/{x}/{y}.png';
        var attr = ' Map data &copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, &copy; <a href="http://cartodb.com/attributions">CartoDB</a>';

        var leafletMap = L.map('mapDiv');

        //创建一个新的图窗格用给定的名字如果不存在,则返回。
        leafletMap.createPane('labels');
        //这个面板是上面的标记,但下面是弹出窗口
        leafletMap.getPane('labels').style.zIndex = 650; //zIndex什么鬼
        //这个面板中的层是非交互的,不影响鼠标/触摸事件。
        leafletMap.getPane('labels').style.pointerEvents = 'none';

        //图层positron 没有国家标签图层
        var positron = L.tileLayer(nolabelsUrl, {
            attribution: attr
        }).addTo(leafletMap);

        //图层positronLabels 有国家标签图层
        var positronLabels = L.tileLayer(lablesUrl, {
            attribution: attr,
            pane: 'labels'
        }).addTo(leafletMap);

        //geojson欧洲国家
        var geojson = L.geoJson(euCountries).addTo(leafletMap);
        //遍历组层,可以选择指定上下文的迭代器函数。
        geojson.eachLayer(function(layer) {
            layer.bindPopup(layer.feature.properties.name); //弹出面板
        });

        leafletMap.setView({
            lat: 47.040182144806664,
            lng: 9.667968750000002
        }, 4);
    </script>

</html>
View Code

显示视频文件

http://leafletjs.com/examples/video-overlay/

传单可以帮助你的地方在地图上显示视频。

<!DOCTYPE html>
<html>

    <head>
        <title>Leaflet11</title>
        <meta charset="utf-8">
        <link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css">
        <script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet.js"></script>
        <style TYPE="text/css">
            body {
                margin: 0px;
                padding: 0px;
            }
            /**
             * 单独设置mapid为100%不显示,可能float坍塌
             */
            
            html,
            body,
            #mapDiv {
                height: 100%;
                width: 100%;
            }
        </style>
    </head>

    <body>
        <div id="mapDiv">
        </div>
    </body>
    <script type="text/javascript" src="http://leafletjs.com/examples/map-panes/eu-countries.js"></script>
    <script>
        //地图地址
        var url = 'https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw';
        var attr = ' Map data &copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, &copy; <a href="http://cartodb.com/attributions">CartoDB</a>';

        var leafletMap = L.map('mapDiv');

        L.tileLayer(url, {
            maxZoom: 18,
            attribution: attr,
            id: 'mapbox.satellite' //卫星图
            //id: 'mapbox.streets'//街道图
        }).addTo(leafletMap);

        //是地图上的一个矩形区域。
        bounds = L.latLngBounds([
            [32, -130],
            [13, -100]
        ]);
        //矩形与marker,circle,polygon,popup类似
        //L.rectangle(bounds).addTo(leafletMap);

        //将地图适应到矩形边界
        leafletMap.fitBounds(bounds);

        var videoUrls = [
            'https://www.mapbox.com/bites/00188/patricia_nasa.webm',
            'https://www.mapbox.com/bites/00188/patricia_nasa.mp4'
        ];
        //用于加载和显示视频播放器在特定范围的地图
        var overlay = L.videoOverlay(videoUrls, bounds, {
            opacity: 0.8, //不透明度
            interactive: true, //如果false,层不会产生鼠标事件,将作为基础地图的一部分。
            autoplay: false //自动播放,否
        });
        leafletMap.addLayer(overlay);
        
        //在leafletMap加载时
        overlay.on('load', function() {
            var MyPauseControl = L.Control.extend({
                onAdd: function() {
                    var button = L.DomUtil.create('button');
                    button.innerHTML = '暂停';
                    //对button增加click事件
                    L.DomEvent.on(button, 'click', function() {
                        overlay.getElement().pause(); //overlay得到html元素,h5之后调用dom的暂停
                    });
                    return button;
                }
            });
            var MyPlayControl = L.Control.extend({
                onAdd: function() {
                    var button = L.DomUtil.create('button');
                    button.innerHTML = '播放';
                    //对button增加click事件
                    L.DomEvent.on(button, 'click', function() {
                        overlay.getElement().play(); //overlay得到html元素,h5之后调用dom的播放
                    });
                    return button;
                }
            });

            var pauseControl = (new MyPauseControl()).addTo(leafletMap);
            var playControl = (new MyPlayControl()).addTo(leafletMap);
        });
    </script>

</html>
View Code
原文地址:https://www.cnblogs.com/scevecn/p/7699145.html