openlayers展示坐标点、连线并实时刷新

//指定地图的位置
<div id="map" class="map"></div>
<script type="text/javascript">
//声明点位信息所需变量
var routeInfos = [];
var routePopups = [];
//声明连线要展示的图层 (图层的添加顺序会用心覆盖效果)
var vector_line;
//声明地图
map = new ol.Map({
    target : 'map',
    view : new ol.View({
        center : ol.proj.transform([105.571776,28.874441],'EPSG:4326', 'EPSG:3857'),
        zoom : 18,
        maxZoom : 19,
        minZoom : 5,
        projection : projection,
    })
});

//为地图添加影像图片
var image_google = new ol.layer.Tile(
        {
            id : 'tianditu',
            title : "影像",
            baseLayer : true,
            source : new ol.source.XYZ(
                    {
                        url: "https://mt" + fRandomBy(0, 3) + ".google.cn/maps/vt?lyrs=s&hl=zh-CN&gl=CN&&x={x}&y={y}&z={z}"
                    }),
            opacity : 1,
        });

map.addLayer(image_google);

//声明展示点位的图层 (图层的添加顺序会影响覆盖效果)

var route_Layer = new ol.layer.Vector({
    id : 'rr'
});
map.addLayer(route_Layer); //增加点位显示的图层

 

//执行方法,加载坐标及连线信息
initRouteInfo();
function initRouteInfo() {
    
    var param = {};
    JSON.stringify(param);
    //============ajax用于获取后台服务提供的坐标信息===============
    $.ajax({
        url: "/getRouteInfo",
        async: true,
        data: JSON.stringify(param), //参数
        method: 'POST',
        dataType: "json",
        cache:false,
        success: function (data) {
            if (data.state) {
                routeInfos = [];
                var routePoints = [];//坐标点位信息
                var routeFeatures = []; //巡检要素

                //声明连线数组
                var coordinatesPolygon = new Array();
                //若线路已展示,清除
                map.removeLayer(vector_line);

                //清除现有地图展示的点位
                for (var m = 0,len=routePopups.length; m < len; m++) {
                    map.removeOverlay(routePopups[m]);
                }
                m= null;

                routePopups  = [];

                //debugger;
                var changdu = data.data.length;
                for( var w = 0; w < changdu; w++){
                  
                    var allRoute = data.data[0];
                    routeInfos.push(allRoute);

                    for (var k = 0, len = allRoute.length; k < len; k++) {
                        var routeinfo = [];//单个坐标点信息
                        if (allRoute[k].lng != undefined
                               && allRoute[k].lng != 0) {
                            routeinfo.push(allRoute[k].lng);
                            routeinfo.push(allRoute[k].lat);
                            routeinfo.push(allRoute[k].mc);
                            routeinfo.push(allRoute[k].zt);

                            routePoints.push(routeinfo);
                        }
                        routeinfo = null;
                    }
                    k = null;
                    allRoute = null;

                }
                w = null;

                //start 根据状态(zt)赋予不同点位不同的样式,生成点要素
                for (var i = 0,len=routePoints.length; i < len; i++) {
                    var iconFeature = new ol.Feature({
                        name : 'station',
                        geometry : new ol.geom.Point(ol.proj
                                .transform([ routePoints[i][0], routePoints[i][1] ],
                                        'EPSG:4326', 'EPSG:3857')),
                        id : routePoints[i][2],
                        x : routePoints[i][0],
                        y : routePoints[i][1]
                    });
                    if(routePoints[i][3]=="ok"){
                        iconFeature.setStyle(StyleFunction(routePoints[i][2],1));//坐标点赋 样式
                        //转换坐标,给需要连线需要的数组赋值(给zt=ok的点位连线,若全部点位连线,放开下面赋值代码即可(6行后))
                        var pointTransform = ol.proj.transform([routePoints[i][0], routePoints[i][1]], 'EPSG:4326', 'EPSG:3857');
                        coordinatesPolygon.push(pointTransform);
                    }else {
                        iconFeature.setStyle(StyleFunction(routePoints[i][2],0));
                    }
                    routeFeatures.push(iconFeature);

                    iconFeature = null;

                    //给连线需要的数组赋值
                    //var pointTransform = ol.proj.transform([routePoints[i][0], routePoints[i][1]], 'EPSG:4326', 'EPSG:3857');
                    //coordinatesPolygon.push(pointTransform);
                }
                route_Layer.setSource(null);
                route_Layer.setSource(new ol.source.Vector({
                    features : routeFeatures
                }));
                i = null;
                routeFeatures = null;
                routePoints = null;

                toline(coordinatesPolygon);
                coordinatesPolygon = null;
            }

            data = null;
        },
       
    });
    //=========================结束============
    param = null;
};
//坐标点 之间画线
function toline(coordinatesPolygon){//直接传入转换后的坐标点数据

    //瓦片图层
    var tileLayer = new ol.layer.Tile({
        source:new ol.source.OSM()
    });
    var source = new ol.source.Vector();
    //矢量图层
    vector_line = new ol.layer.Vector({
        source: source,
        style: new ol.style.Style({
            fill: new ol.style.Fill({
                color: 'rgba(255, 255, 255, 0.1)'
            }),
            stroke: new ol.style.Stroke({//地图连线的样式
                color: 'red',//颜色
                width: 10//宽度
            }),
            image: new ol.style.Circle({
                radius: 10,
                fill: new ol.style.Fill({
                    color: '#ffcc33'
                })
            })
        })
    });
    //多边形此处注意一定要是[坐标数组]
    console.log("画线的坐标集合为="+coordinatesPolygon);
    var plygon = new ol.geom.Polygon([coordinatesPolygon])
    //多边形要素类
    var feature = new ol.Feature({
        geometry: plygon,
    });

    source.addFeature(feature);

    map.addLayer(vector_line);


}

//给坐标点赋值样式

function  StyleFunction(name,type) {
    if(type==1) {
        return new ol.style.Style({
            image : new ol.style.Icon(
                    {
                        anchor : [ 0.5, 1 ],
                        //anchorXUnits: 'fraction',
                        //anchorYUnits: 'pixels',
                        src : '${pageContext.request.contextPath}/resources/lib/gislib/imgs/routenormal.png'
                    })
            //text: createTextStyle(name)//坐标点名称,需要可以显示
        });
    }else {
        return new ol.style.Style({
            image : new ol.style.Icon(
                    {
                        anchor : [ 0.5, 1 ],
                        //anchorXUnits: 'fraction',
                        //anchorYUnits: 'pixels',
                        src : '${pageContext.request.contextPath}/resources/lib/gislib/imgs/routeerror.png'
                    })
            //text: createTextStyle(name)//坐标点名称,需要可以显示
        });
    }
}

//坐标点 显示名称

function createTextStyle(name) {
    return new ol.style.Text({
        text: name,
        offsetX: 0,
        offsetY: -197,
        fill: new ol.style.Fill({
            color: 'white'
        }),

        font: 'bold 26px 微软雅黑,sans-serif',

    });
};
function fRandomBy(under, over) {
    switch (arguments.length) {
        case 1:
            return parseInt(Math.random() * under + 1);
        case 2:
            return parseInt(Math.random() * (over - under + 1) + under);
        default:
            return 0;
    }
}

</script>

 

最后附上效果图,如下(本图效果是先添加的坐标点位route_layer,线的连接覆盖了点,若线连接不覆盖点,先add线的图层

vector_line即可.

)

### 回答1: OpenLayers 5 是一个开源的 JavaScript 库,用于创建交互式地图应用。要实现在地图上绘制坐标之间的连线,可以按照以下步骤进行: 1. 首先,在 HTML 文件中导入 OpenLayers 库和样式文件: ```html <link rel="stylesheet" href="https://openlayers.org/en/v5.3.0/css/ol.css" /> <script src="https://openlayers.org/en/v5.3.0/build/ol.js"></script> ``` 2. 创建一个地图容器的 div 元素: ```html <div id="map" style="width: 400px; height: 300px;"></div> ``` 3. 在 JavaScript 文件中,创建一个用于显示地图的 map 对象: ```javascript var map = new ol.Map({ target: 'map', layers: [ new ol.layer.Tile({ source: new ol.source.OSM() }) ], view: new ol.View({ center: ol.proj.fromLonLat([0, 0]), zoom: 2 }) }); ``` 4. 创建一个矢量图层和一个矢量源对象: ```javascript var vectorLayer = new ol.layer.Vector({ source: new ol.source.Vector() }); map.addLayer(vectorLayer); var vectorSource = vectorLayer.getSource(); ``` 5. 为地图添加单击事件,获取击位置的坐标: ```javascript map.on('click', function(event) { var coordinate = event.coordinate; // 在此处可以将坐标添加到 vectorSource 中 }); ``` 6. 在单击事件的回调函数中,创建一个要素并添加到矢量源对象中: ```javascript var pointFeature = new ol.Feature({ geometry: new ol.geom.Point(coordinate) }); vectorSource.addFeature(pointFeature); ``` 7. 如果要连接这些坐标,可以使用 ol.geom.LineString 创建一个线要素,然后添加到矢量源对象中: ```javascript var lineStringFeature = new ol.Feature({ geometry: new ol.geom.LineString(coordinates) }); vectorSource.addFeature(lineStringFeature); ``` 最后,你将在地图上看到所有的坐标以及它们之间的连线。这是使用 OpenLayers 5 实现坐标线的基本步骤。可以通过进一步自定义样式和处理事件来增加功能。 ### 回答2: OpenLayers 5是一个开源的JavaScript库,可用于在Web上实现地图功能。如果要在地图上绘制坐标之间的连线,可以按照以下步骤进行: 1. 初始化地图:首先,需要在页面上创建一个地图容器,然后初始化地图对象。可以指定地图的中心坐标、缩放级别等属性。 2. 添加图层:接下来,创建一个矢量图层,并将其添加到地图中。这样可以在地图上绘制矢量要素,如线、面等。 3. 创建要素:使用OpenLayers的Point类,可以创建一个要素,其中包含要绘制的坐标的经纬度信息。 4. 创建线要素:使用OpenLayers的LineString类,可以创建一个线要素,其中包含要绘制的坐标序列。 5. 绘制要素:将要素添加到图层中,再将线要素添加到图层中。这样,地图上就可见了这些要素。 以下是一个示例代码片段,展示了如何在OpenLayers 5中实现坐标线的功能: ```javascript // 初始化地图 var map = new ol.Map({ target: 'map-container', layers: [ new ol.layer.Tile({ source: new ol.source.OSM() }) ], view: new ol.View({ center: ol.proj.fromLonLat([0, 0]), zoom: 10 }) }); // 创建矢量图层 var vectorLayer = new ol.layer.Vector({ source: new ol.source.Vector() }); map.addLayer(vectorLayer); // 创建要素 var point1 = new ol.Feature({ geometry: new ol.geom.Point(ol.proj.fromLonLat([lon1, lat1])) }); var point2 = new ol.Feature({ geometry: new ol.geom.Point(ol.proj.fromLonLat([lon2, lat2])) }); // 创建线要素 var lineFeature = new ol.Feature({ geometry: new ol.geom.LineString([ ol.proj.fromLonLat([lon1, lat1]), ol.proj.fromLonLat([lon2, lat2]) ]) }); // 添加要素到图层 vectorLayer.getSource().addFeature(point1); vectorLayer.getSource().addFeature(point2); vectorLayer.getSource().addFeature(lineFeature); ``` 以上代码中的`map-container`是在HTML页面上用来容纳地图的一个元素,`lon1`、`lat1`、`lon2`和`lat2`是两个坐标的经纬度值。通过将要素和线要素添加到矢量图层中,即可在地图上看到这些要素,实现坐标的划线功能。 ### 回答3: 使用OpenLayers 5实现坐标线的方法如下: 首先,创建一个地图容器,可以使用HTML中的一个div元素作为容器: ```html <div id="map" style="width: 100%; height: 500px;"></div> ``` 然后,在JavaScript中,创建一个OpenLayers地图实例并将其显示在地图容器中: ```javascript var map = new ol.Map({ target: 'map', layers: [ new ol.layer.Tile({ source: new ol.source.OSM() }) ], view: new ol.View({ center: ol.proj.fromLonLat([0, 0]), zoom: 4 }) }); ``` 接下来,创建一个用于存储坐标的数组: ```javascript var coordinates = [ [0, 0], // 第一个的经纬度 [10, 10], // 第二个的经纬度 [20, 20], // 第三个的经纬度 // ... ]; ``` 然后,使用OpenLayers的Vector模块创建一个特征集合,并将坐标添加到特征集合中: ```javascript var features = new ol.Collection(); var feature = new ol.Feature({ geometry: new ol.geom.LineString(coordinates) }); features.push(feature); ``` 再创建一个用于显示特征集合的矢量层: ```javascript var vectorLayer = new ol.layer.Vector({ source: new ol.source.Vector({ features: features }) }); ``` 最后,将矢量层添加到地图上,就可以在地图上显示坐标的划线了: ```javascript map.addLayer(vectorLayer); ``` 需要注意的是,以上代码只是一个简单示例,实际应用中您可能需要根据具体需求调整参数和添加其他功能。此外,还需要确保引入了OpenLayers的JavaScript文件。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值