Openlayers学习入门

Openlayers学习入门


参考资料: http://weilin.me

1. 在同一个界面动态交换地图


<html xmlns=http://www.w3.org/1999/xhtml>
<head>
    <meta http-equiv=Content-Type content="text/html;charset=utf-8">
    <meta http-equiv=X-UA-Compatible content="IE=edge,chrome=1">
    <meta content=always name=referrer>
    <title>OpenLayers 3地图示例title>
    <link href="ol.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="ol.js" charset="utf-8">script>
head>

<body>
    <p>地图1p>
    <div id="map1" style="width: 100%, height: 400px">div>
    <p>地图2p>
    <div id="map2" style="width: 100%, height: 400px">div>
    <input type="button" onClick="swapMap();" value="调换地图"/>
    <script>
      // 创建地图
      var map1 = new ol.Map({
          controls: ol.control.defaults({
              attributionOptions: ({
                  collapsible: false
              })
          }),
          logo: {src: 'http://weilin.me/ol3-primer/img/face_monkey.png', href: 'http://www.openstreetmap.org/'},
            // 设置地图图层
            layers: [
              // 创建一个使用Open Street Map地图源的瓦片图层
              new ol.layer.Tile({source: new ol.source.OSM()})
            ],
            // 设置显示地图的视图
            view: new ol.View({
              center: [0, 0],    // 定义地图显示中心于经度0度,纬度0度处
              zoom: 2            // 并且定义地图显示层级为2
            }),
            // 让id为map的div作为地图的容器
            target: 'map1'
        });
          var map2 = new ol.Map({
          controls: ol.control.defaults({
              attributionOptions: ({
                  collapsible: false
              })
          }),
          logo: {src: 'http://weilin.me/ol3-primer/img/face_monkey.png', href: 'http://www.openstreetmap.org/'},
            // 设置地图图层
            layers: [
              // 创建一个使用Open Street Map地图源的瓦片图层
              new ol.layer.Tile({source: new ol.source.OSM()})
            ],
            // 设置显示地图的视图
            view: new ol.View({
              center: [0, 0],    // 定义地图显示中心于经度0度,纬度0度处
              zoom: 2            // 并且定义地图显示层级为2
            }),
            // 让id为map的div作为地图的容器
            target: 'map2'
        });
            
            function swapMap() {
                map1.setTarget('map2');
                map2.setTarget('map1');
            }
            
    script>
body>

html>

2. 点击地图下方的按钮实现地图导航功能


<html xmlns=http://www.w3.org/1999/xhtml>
<head>
    <meta http-equiv=Content-Type content="text/html;charset=utf-8">
    <meta http-equiv=X-UA-Compatible content="IE=edge,chrome=1">
    <meta content=always name=referrer>
    <title>OpenLayers 3地图示例title>
    <link href="ol.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="ol.js" charset="utf-8">script>
head>

<body>
    <div id="map" style="width: 100%, height: 400px">div>
    <div id="navigate-container">
        <input type="button" onClick="moveToLeft();" value="左移"/>
        <input type="button" onClick="moveToRight();" value="右移" />
        <input type="button" onClick="moveToUp();" value="上移" />
        <input type="button" onClick="moveToDown();" value="下移" />
        <input type="button" onClick="moveToChengDu();" value="移到成都" />
        <input type="button" onClick="zoomIn();" value="放大" />
        <input type="button" onClick="zoomOut();" value="缩小" />
    div>
    <script>
      // 创建地图
      var map = new ol.Map({
          controls: ol.control.defaults({
              attributionOptions: ({
                  collapsible: false
              })
          }),
          logo: {src: 'http://weilin.me/ol3-primer/img/face_monkey.png', href: 'http://www.openstreetmap.org/'},
            // 设置地图图层
            layers: [
              // 创建一个使用Open Street Map地图源的瓦片图层
              new ol.layer.Tile({source: new ol.source.OSM()})
            ],
            // 设置显示地图的视图
            view: new ol.View({
              // 设置成都为地图中心,此处进行坐标转换, 把EPSG:4326的坐标,转换为EPSG:3857坐标,因为ol默认使用的是EPSG:3857坐标
                center: ol.proj.transform([104.06, 30.67], 'EPSG:4326', 'EPSG:3857'),
                zoom: 10
            }),
            // 让id为map的div作为地图的容器
            target: 'map'
        });
        // 向左移动地图
        function moveToLeft() {
            var view = map.getView();
            var mapCenter = view.getCenter();
            // 让地图中心的x值增加,即可使得地图向左移动,增加的值根据效果可自由设定
            mapCenter[0] += 50000;
            view.setCenter(mapCenter);
            map.render();
        }
        // 向右移动地图
        function moveToRight() {
            var view = map.getView();
            var mapCenter = view.getCenter();
            // 让地图中心的x值减少,即可使得地图向右移动,减少的值根据效果可自由设定
            mapCenter[0] -= 50000;
            view.setCenter(mapCenter);
            map.render();
        }

        // 向上移动地图
        function moveToUp() {
            var view = map.getView();
            var mapCenter = view.getCenter();
            // 让地图中心的y值减少,即可使得地图向上移动,减少的值根据效果可自由设定
            mapCenter[1] -= 50000;
            view.setCenter(mapCenter);
            map.render();
        }

        // 向下移动地图
        function moveToDown() {
            var view = map.getView();
            var mapCenter = view.getCenter();
            // 让地图中心的y值增加,即可使得地图向下移动,增加的值根据效果可自由设定
            mapCenter[1] += 50000;
            view.setCenter(mapCenter);
            map.render();
        }

        // 移动到成都
        function moveToChengDu() {
            var view = map.getView();
            // 设置地图中心为成都的坐标,即可让地图移动到成都
            view.setCenter(ol.proj.transform([104.06, 30.67], 'EPSG:4326', 'EPSG:3857'));
            map.render();
        }

        // 放大地图
        function zoomIn() {
            var view = map.getView();
            // 让地图的zoom增加1,从而实现地图放大
            view.setZoom(view.getZoom() + 1);
        }

        // 缩小地图
        function zoomOut() {
            var view = map.getView();
            // 让地图的zoom减小1,从而实现地图缩小
            view.setZoom(view.getZoom() - 1);
        }
            
    script>
body>

html>

3. 加载不同的在线地图


<html xmlns=http://www.w3.org/1999/xhtml>
<head>
    <meta http-equiv=Content-Type content="text/html;charset=utf-8">
    <meta http-equiv=X-UA-Compatible content="IE=edge,chrome=1">
    <meta content=always name=referrer>
    <title>OpenLayers 3地图示例title>
    <link href="ol.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="ol.js" charset="utf-8">script>
head>

<body>
    <div id="map" style="width: 100%">div>
        <input type="radio" checked="checked" name="mapSource" onclick="switch2OSM();" />OpenStreetMap地图
        <input type="radio" name="mapSource" onclick="switch2BingMap();" />Bing地图
        <input type="radio" name="mapSource" onclick="switch2StamenMap();" />Stamen地图
    <script>
        // Open Street Map 地图层
        var openStreetMapLayer = new ol.layer.Tile({
            source: new ol.source.OSM()
        });

        // Bing地图层
        var bingMapLayer = new ol.layer.Tile({
            source: new ol.source.BingMaps({
                key: 'AkjzA7OhS4MIBjutL21bkAop7dc41HSE0CNTR5c6HJy8JKc7U9U9RveWJrylD3XJ',
          imagerySet: 'Road'
            })
        });

        // Stamen地图层
        var stamenLayer = new ol.layer.Tile({
            source: new ol.source.Stamen({
                layer: 'watercolor'
            })
        });

        var map = new ol.Map({
            layers: [
                openStreetMapLayer
            ],
            view: new ol.View({
                // 设置成都为地图中心
                center: ol.proj.transform([104.06, 30.67], 'EPSG:4326', 'EPSG:3857'),
                zoom: 10,
                minZoom: 10,
                maxZoom: 14
            }),
            target: 'map'
      });
      function switch2OSM() {
          // 先移除当前的地图,再添加Open Street Map 地图
          map.removeLayer(map.getLayers().item(0));
          map.addLayer(openStreetMapLayer);
      }

      function switch2BingMap() {
          // 先移除当前的地图,再添加Bing地图
          map.removeLayer(map.getLayers().item(0));
          map.addLayer(bingMapLayer);
      }

      function switch2StamenMap() {
          // 先移除当前的地图,再添加stamen地图
          map.removeLayer(map.getLayers().item(0));
          map.addLayer(stamenLayer);
      }
    script>
body>

html>

4. 其它方式加载地图layers

//Open Street Map
var openStreetMapLayer = new ol.layer.Tile({
            source: new ol.source.XYZ({
                url: 'http://{a-c}.tile.openstreetmap.org/{z}/{x}/{y}.png'
            })
        });

// 高德地图层
var gaodeMapLayer = new ol.layer.Tile({
    source: new ol.source.XYZ({
        url:'http://webst0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}'
    })
});

// yahoo地图层
var yahooMapLayer = new ol.layer.Tile({
    source: new ol.source.XYZ({
        tileSize: 512,
        url:'https://{0-3}.base.maps.api.here.com/maptile/2.1/maptile/newest/normal.day/{z}/{x}/{y}/512/png8?lg=ENG&ppi=250&token=TrLJuXVK62IQk0vuXFzaig%3D%3D&requestid=yahoo.prod&app_id=eAdkWGYRoc4RfxVo0Z4B'
    })
});

5. 瓦片加载原理debug示意图


<html xmlns=http://www.w3.org/1999/xhtml>
<head>
    <meta http-equiv=Content-Type content="text/html;charset=utf-8">
    <meta http-equiv=X-UA-Compatible content="IE=edge,chrome=1">
    <meta content=always name=referrer>
    <title>OpenLayers 3地图示例title>
    <link href="ol.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="ol.js" charset="utf-8">script>
head>

<body>
    <div id="map" style="width: 100%">div>
    <script>
        var resolutions = [];
        var tileSize = 256;
        var extent = [12665080.52765571, 2550703.6338763316, 12725465.780000998, 2601457.820657688]; //深圳地区
        var projection = new ol.proj.get("EPSG:3857");
        var projectionExtent = projection.getExtent();

        for (var i = 0; i < 19; i++) {
            resolutions[i] = Math.pow(2, 18 - i);
        }

        var tilegrid = new ol.tilegrid.TileGrid({
            origin: ol.extent.getBottomLeft(projectionExtent),
            resolutions: resolutions,
            extent: projectionExtent,//extent,
            tileSize: [256, 256],
        });

        var map = new ol.Map({
            target: "map",
            layers: [
            // 调试瓦片
            new ol.layer.Tile({
                source: new ol.source.TileDebug({
                projection: projection,
                tileGrid: tilegrid,
                tileSize: [256, 256],
                extent :  projectionExtent,
                wrapX: false
                }),
            })
            ],
            view: new ol.View({
            projection: projection,
            center: [12697184.079535482, 2563239.3065151004],//深圳
            resolutions: resolutions,
            }),
        });
        map.getView().setZoom(1);
    script>
body>

html>

6. 给地图加activity小图标


<html xmlns=http://www.w3.org/1999/xhtml>
<head>
    <meta http-equiv=Content-Type content="text/html;charset=utf-8">
    <meta http-equiv=X-UA-Compatible content="IE=edge,chrome=1">
    <meta content=always name=referrer>
    <title>OpenLayers 3地图示例title>
    <link href="ol.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="ol.js" charset="utf-8">script>
head>

<body>
    <div id="map" style="width: 100%">div>
    <script type="text/javascript">
        // 地图设置中心,设置到成都,在本地离线地图 offlineMapTiles刚好有一张zoom为4的成都瓦片
        var center = ol.proj.transform([104.06667, 30.66667], 'EPSG:4326', 'EPSG:3857');
        // 计算熊猫基地地图映射到地图上的范围,图片像素为 550*344,保持比例的情况下,把分辨率放大一些
        var extent = [center[0]- 550*1000/2, center[1]-344*1000/2, center[0]+550*1000/2, center[1]+344*1000/2];

        //创建地图
        var map = new ol.Map({
            view: new ol.View({
                center: center,
                zoom: 7
            }),
            target: 'map'
        });

        // 加载熊猫基地静态地图层
        map.addLayer(new ol.layer.Image({
            source: new ol.source.ImageStatic({
                url: 'http://weilin.me/ol3-primer/img/pandaBase.jpg', // 熊猫基地地图
                imageExtent: extent     // 映射到地图的范围
            })
        }));
        // 创建一个用于放置活动图标的layer
        var activityLayer = new ol.layer.Vector({
            source: new ol.source.Vector()
        });
        // 创建一个活动图标需要的Feature,并设置位置
        var activity = new ol.Feature({
            geometry: new ol.geom.Point([center[0]- 550*1000/2 + 390 * 1000, center[1]-344*1000/2 + (344 - 145) * 1000])
        })
        // 设置Feature的样式,使用小旗子图标
        activity.setStyle(new ol.style.Style({
            image: new ol.style.Icon({
                src: 'http://weilin.me/ol3-primer/img/flag_right.png',
                anchor: [0, 1],
                scale: 0.2
            })
        }));
        // 添加活动Feature到layer上,并把layer添加到地图中
        activityLayer.getSource().addFeature(activity);
        map.addLayer(activityLayer);
    script>
body>

html>

你可能感兴趣的:(Openlayers)