openlayer使用

1、定义

OpenLayers 是一个高性能、功能丰富的库,用于在 Web 上创建交互式地图。它可以显示从任何来源加载的地图图块、矢量数据和标记。

官方文档

引用ol.js和ol.css即可使用

2、覆盖物

主要有marker图标、线、图形(圆形、正方形等)

<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>map</title>
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <meta http-equiv="Cache-Control" content="no-siteapp"/>
    <link rel="stylesheet" th:href="@{/css/bootstrap.min.css}">
    <link rel="stylesheet" th:href="@{/css/map.css}">
    <link rel="stylesheet" th:href="@{/js/openlayer/ol.css}">

</head>
<body>
<select id="type">
    <option value="marker">marker</option>
    <option value="line">line</option>
    <option value="circle">circle</option>
    <option value="infoWindow">infoWindow</option>
</select>
<button id="drawOverlay">随机生成</button>
<div class="container" id="map"></div>


<div id="overlay" style="display: none;" class="tooltip tooltip-measure">
</div>
<script th:src="@{/js/jquery-1.9.1.js}" type="text/javascript"></script>
<script th:src="@{/js/bootstrap.min.js}" type="text/javascript"></script>
<script th:src="@{/js/openlayer/ol.js}" type="text/javascript"></script>
<script type="text/javascript">

    var map;
    $(function () {
        init_map();
        init_select_event();
    });

    function init_select_event(){
        $("#drawOverlay").click(function(){
            var key= $("#type").val();
            if(key=="circle"){
                drawCircle();
            }else if(key=="marker"){
                drawMarker();
            }else if(key=="line"){
                drawLine();
            }else if(key=="infoWindow"){
                addInfoWindow();
            }
        })
    }

    var source = new ol.source.Vector({});

    var vector = new ol.layer.Vector({
        source: source,
        style: new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: 'yellow',
                width: 4
            }),
            fill: new ol.style.Fill({
                color: 'blue'
            })
        })
    });

    var gaode=new ol.layer.Tile({
        source:new ol.source.XYZ({
            tileUrlFunction:function (coord) {
                var z=coord[0];
                var x=coord[1];
                var y=-coord[2]-1;
                var url='http://mt2.google.cn/vt/lyrs=m&scale=2&hl=zh-CN&gl=cn';
                url+="&x=" + x+ "&y=" + y+ "&z="+z;
                return url;
            }
        })
    });

    function init_map(){
        map=new ol.Map({
            layers:[gaode,vector],
            view:new ol.View({
                center:[118.78,32.07],
                projection:'EPSG:4326',
                zoom:14
            }),
            target:'map'
        });
    }


    function panTo(lat,lng){
        map.getView().setCenter([lng,lat]);
    }


    function pad(num,n){
        n = n || 6;
        var len = num.toString().length;
        while (len < n) {
            num = "0" + num;
            len++;
        }
        return num;
    }

    function drawCircle(){

        var lng=118+Math.random();
        var lat=32+Math.random();
        var circle=new ol.geom.Circle([lng,lat],0.01);
        var feature=new ol.Feature({
            geometry:circle
        });
        var style=new ol.style.Style({
            stroke:new ol.style.Stroke({
                color:'red'
            }),
            fill:new ol.style.Fill({
                color:'red'
            })
        });
        source.addFeature(feature);
        feature.setStyle(style);
        panTo(lat,lng);
    }

    var markerCount=0;

    function drawMarker(){
        markerCount++;
        var lat=32.5+Math.random()/2;
        var lng=118.5+Math.random()/2;
        var marker = new ol.Feature({
            geometry:new ol.geom.Point([lng,lat])
        });

        marker.setStyle(new ol.style.Style({
                image:new ol.style.Icon({
                    src:'/map/images/map_red_bg.png',
                    scale:1
                }),
            text:new ol.style.Text({
                text:''+markerCount,
                fill:new ol.style.Fill({
                    color:'white'
                }),
                font:'20px sans-serif'
            })
            })
        );


        source.addFeature(marker);
        panTo(lat,lng);

    }

    function drawLine(){
        var lng=118+Math.random();
        var lat=32+Math.random();
        var lng2=lng+1;
        var lat2=lat+1;


        var coordinates=[ [lng,lat],[lng2,lat2] ];
        var line=new ol.geom.LineString(coordinates);
        var feature=new ol.Feature({
            geometry:line
        });

        source.addFeature(feature);
        panTo(lat,lng);
    }

    function addInfoWindow(){
        var lat=118.5+Math.random()/2;
        var lng=32.5+Math.random()/2;
        var overlay=new ol.Overlay({
            id:'effc3',
            element:document.getElementById('overlay'),
            position:[lng,lat],
        });
        map.addOverlay(overlay);
        $("#overlay").html("hello world");
        $("#overlay").show();
        panTo(lat,lng);
    }



</script>

</body>
</html>

map1

2、框选交互、包括圆形选择、框选以及其他不规则图形

<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>map</title>
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <meta http-equiv="Cache-Control" content="no-siteapp"/>
    <link rel="stylesheet" th:href="@{/css/bootstrap.min.css}">
    <link rel="stylesheet" th:href="@{/js/openlayer/ol.css}">

</head>
<body>
<div class="main" style="display: flex;flex-direction: row;justify-content: space-between">
    <div class="left" style="width:30%; ">
        <select id="type">
            <option value="LineString">LineString</option>
            <option value="Circle">Circle</option>
            <option value="Star">Star</option>
            <option value="Box">Box</option>
            <option value="Square">Square</option>
            <option value="Polygon">Polygon</option>
        </select>
        <textarea id="showCoordinate" rows="20" cols="80"></textarea>
    </div>

    <div class="right" style="width: 70%">
        <div class="container" id="map"></div>
    </div>
</div>




<script th:src="@{/js/jquery-1.9.1.js}" type="text/javascript"></script>
<script th:src="@{/js/bootstrap.min.js}" type="text/javascript"></script>
<script th:src="@{/js/openlayer/ol.js}" type="text/javascript"></script>
<script type="text/javascript" th:inline="javascript">

    var map;
    $(function () {
        init_map();
        addInteraction();
    });

    var source = new ol.source.Vector({wrapX: false});

    var vector = new ol.layer.Vector({
        source: source
    });

    var gaode=new ol.layer.Tile({
        source:new ol.source.XYZ({
            tileUrlFunction:function (coord) {
                var z=coord[0];
                var x=coord[1];
                var y=-coord[2]-1;
                var url='http://mt2.google.cn/vt/lyrs=m&scale=2&hl=zh-CN&gl=cn';
                url+="&x=" + x+ "&y=" + y+ "&z="+z;
                return url;
            }
        })
    });

    function init_map(){
        interaction=new ol.Map({
            layers:[gaode,vector],
            view:new ol.View({
                center:[118.78,32.07],
                projection:'EPSG:4326',
                zoom:14
            }),
            target:'map'
        })
    }

    function pad(num,n){
        n = n || 6;
        var len = num.toString().length;
        while (len < n) {
            num = "0" + num;
            len++;
        }
        return num;
    }

    var typeSelect = document.getElementById('type');

    var draw; // global so we can remove it later
    function addInteraction() {
        var value = typeSelect.value;
        if (value !== 'None') {
            var geometryFunction;
            if (value === 'Square') {
                value = 'Circle';
                geometryFunction = ol.interaction.Draw.createRegularPolygon(4);
            } else if (value === 'Box') {
                value = 'Circle';
                geometryFunction = ol.interaction.Draw.createBox();
            } else if (value === 'Star') {
                value = 'Circle';
                geometryFunction = function(coordinates, geometry) {
                    var center = coordinates[0];
                    var last = coordinates[1];
                    var dx = center[0] - last[0];
                    var dy = center[1] - last[1];
                    var radius = Math.sqrt(dx * dx + dy * dy);
                    var rotation = Math.atan2(dy, dx);
                    var newCoordinates = [];
                    var numPoints = 12;
                    for (var i = 0; i < numPoints; ++i) {
                        var angle = rotation + i * 2 * Math.PI / numPoints;
                        var fraction = i % 2 === 0 ? 1 : 0.5;
                        var offsetX = radius * fraction * Math.cos(angle);
                        var offsetY = radius * fraction * Math.sin(angle);
                        newCoordinates.push([center[0] + offsetX, center[1] + offsetY]);
                    }
                    newCoordinates.push(newCoordinates[0].slice());
                    if (!geometry) {
                        geometry = new ol.geom.Polygon([newCoordinates]);
                    } else {
                        geometry.setCoordinates([newCoordinates]);
                    }
                    return geometry;
                };
            }
            draw = new ol.interaction.Draw({
                source: source,
                type: value,
                geometryFunction: geometryFunction
            });
            draw.on('drawend',function (evt) {
                var poly=evt.feature.getGeometry();
                var text=""
                if(poly.getType()=="Circle"){
                    text="中心:"+JSON.stringify(poly.getCenter());
                    text+="\n";
                    text+="半径:"+poly.getRadius();
                }else{
                    text=JSON.stringify(poly.getCoordinates());
                }
                $("#showCoordinate").val(text);
            })
            interaction.addInteraction(draw);
        }
    }


    /**
     * Handle change event.
     */
    typeSelect.onchange = function() {
        interaction.removeInteraction(draw);
        addInteraction();
    };

</script>
</body>
</html>

map2

3、热力图

<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>map</title>
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <meta http-equiv="Cache-Control" content="no-siteapp"/>
    <link rel="stylesheet" th:href="@{/css/bootstrap.min.css}">
    <link rel="stylesheet" th:href="@{/css/map.css}">
    <link rel="stylesheet" th:href="@{/js/openlayer/ol.css}">

</head>
<body>
<select id="type">
    <option value="marker">marker</option>
    <option value="line">line</option>
    <option value="circle">circle</option>
    <option value="infoWindow">infoWindow</option>
</select>
<button id="drawOverlay">随机生成</button>
<div class="container" id="map"></div>


<div id="overlay" style="display: none;" class="tooltip tooltip-measure">
</div>
<script th:src="@{/js/jquery-1.9.1.js}" type="text/javascript"></script>
<script th:src="@{/js/bootstrap.min.js}" type="text/javascript"></script>
<script th:src="@{/js/openlayer/ol.js}" type="text/javascript"></script>
<script type="text/javascript">

    var map;
    $(function () {
        init_map();
        init_select_event();
    });

    function init_select_event(){
        $("#drawOverlay").click(function(){
            var key= $("#type").val();
            if(key=="circle"){
                drawCircle();
            }else if(key=="marker"){
                drawMarker();
            }else if(key=="line"){
                drawLine();
            }else if(key=="infoWindow"){
                addInfoWindow();
            }
        })
    }

    var source = new ol.source.Vector({});

    var vector = new ol.layer.Vector({
        source: source,
        style: new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: 'yellow',
                width: 4
            }),
            fill: new ol.style.Fill({
                color: 'blue'
            })
        })
    });

    var gaode=new ol.layer.Tile({
        source:new ol.source.XYZ({
            tileUrlFunction:function (coord) {
                var z=coord[0];
                var x=coord[1];
                var y=-coord[2]-1;
                var url='http://mt2.google.cn/vt/lyrs=m&scale=2&hl=zh-CN&gl=cn';
                url+="&x=" + x+ "&y=" + y+ "&z="+z;
                return url;
            }
        })
    });

    function init_map(){
        map=new ol.Map({
            layers:[gaode,vector],
            view:new ol.View({
                center:[118.78,32.07],
                projection:'EPSG:4326',
                zoom:14
            }),
            target:'map'
        });
    }


    function panTo(lat,lng){
        map.getView().setCenter([lng,lat]);
    }


    function pad(num,n){
        n = n || 6;
        var len = num.toString().length;
        while (len < n) {
            num = "0" + num;
            len++;
        }
        return num;
    }

    function drawCircle(){

        var lng=118+Math.random();
        var lat=32+Math.random();
        var circle=new ol.geom.Circle([lng,lat],0.01);
        var feature=new ol.Feature({
            geometry:circle
        });
        var style=new ol.style.Style({
            stroke:new ol.style.Stroke({
                color:'red'
            }),
            fill:new ol.style.Fill({
                color:'red'
            })
        });
        source.addFeature(feature);
        feature.setStyle(style);
        panTo(lat,lng);
    }

    var markerCount=0;

    function drawMarker(){
        markerCount++;
        var lat=32.5+Math.random()/2;
        var lng=118.5+Math.random()/2;
        var marker = new ol.Feature({
            geometry:new ol.geom.Point([lng,lat])
        });

        marker.setStyle(new ol.style.Style({
                image:new ol.style.Icon({
                    src:'/map/images/map_red_bg.png',
                    scale:1
                }),
            text:new ol.style.Text({
                text:''+markerCount,
                fill:new ol.style.Fill({
                    color:'white'
                }),
                font:'20px sans-serif'
            })
            })
        );


        source.addFeature(marker);
        panTo(lat,lng);

    }

    function drawLine(){
        var lng=118+Math.random();
        var lat=32+Math.random();
        var lng2=lng+1;
        var lat2=lat+1;


        var coordinates=[ [lng,lat],[lng2,lat2] ];
        var line=new ol.geom.LineString(coordinates);
        var feature=new ol.Feature({
            geometry:line
        });

        source.addFeature(feature);
        panTo(lat,lng);
    }

    function addInfoWindow(){
        var lat=118.5+Math.random()/2;
        var lng=32.5+Math.random()/2;
        var overlay=new ol.Overlay({
            id:'effc3',
            element:document.getElementById('overlay'),
            position:[lng,lat],
        });
        map.addOverlay(overlay);
        $("#overlay").html("hello world");
        $("#overlay").show();
        panTo(lat,lng);
    }



</script>

</body>
</html>

map3

results matching ""

    No results matching ""