官术网_书友最值得收藏!

Showing a map with a path

When displaying maps, sometimes we may want to show more than just locations. Besides markers, the other most common map overlays are paths and areas.

In this recipe, we're going to create a map showing a path and an area.

How to do it...

Let's write the HTML and JavaScript code.

  1. Like in the Showing a map with a marked location recipe, we'll need to include the appropriate CSS and scripts. The following is an example HTML file:
    <!DOCTYPE HTML>
    <html>
        <head>
            <title>Map example</title>
            <link rel="stylesheet"  />
            <!--[if lte IE 8]>
            <link rel="stylesheet"  />
            <![endif]-->
        </head>
        <body>
            <div id="map" style="height:480px; width:640px;"></div>
            <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
            <script src="http://cdn.leafletjs.com/leaflet-0.4/leaflet.js"></script>
            <script type="text/javascript" src="example.js"></script>
        </body>
    </html>
  2. Then we can add our code to example.js:
    var map = L.map('map').setView([52.513, -0.06], 14)
    
    L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',{
        attribution:'Copyright (C) OpenStreetMap.org',
        maxZoom:18
    }).addTo(map);
    
    var polyline = L.polyline([
        [52.519, -0.08],
        [52.513, -0.06],
        [52.52, -0.047]
    ]).addTo(map);
    
    
    var polygon = L.polygon([
        [52.509, -0.08],
        [52.503, -0.06],
        [52.51, -0.047]
    ], {
        color:"#f5f",
        stroke: false,
        fillOpacity:0.5
    }).addTo(map);

How it works...

We create our map using the L.map function and set the map's position using setView at the specified [latitude, longitude] array and the zoom level. We also add the standard OpenStreetMap tile layer.

First we create and add a standard polyline. As we don't specify any options, Leaflet uses reasonable defaults for colors, opacity, borders, and so on. The polyline constructor takes an array of [latitude, longitude] pairs and draws a line with vertices that go through them.

Afterwards, we create a slightly customized polygon. Like the polyline constructor, the polygon also takes an array of [latitude, longitude] pairs. Additionally, we customize the background color, remove the polygon's border, and specify the polygon's opacity to be 50 percent.

主站蜘蛛池模板: 金门县| 垦利县| 丁青县| 长阳| 南通市| 柳州市| 西吉县| 黎平县| 甘孜县| 娄底市| 上饶市| 年辖:市辖区| 南陵县| 义马市| 晋江市| 哈尔滨市| 富裕县| 贡山| 姜堰市| 临漳县| 河东区| 奇台县| 那坡县| 阿巴嘎旗| 望奎县| 喀喇| 黔西县| 林州市| 清苑县| 镇原县| 宿迁市| 德钦县| 文成县| 嵊州市| 张掖市| 临朐县| 麻城市| 盐津县| 阿克| 来安县| 始兴县|