OpenLayers(1)


1.MAP:

// 创建地图
var map =new ol.Map({
                layers: [
                          vecLayer,//天地图矢量图层
                          sdmapLayer,//天地图山东矢量图层 -- 标注省界及地市,道路等名称
                          sdxzjLayer,//山东行政界--行政区划数据服务
                          sdjiaotongLayer,//山东交通(高速、国道、省道、铁路等)
                          drawLayerVector,//将绘制层添加到地图容器中
                          advertMarkerLayer// 广告牌标注图层
                ],
                controls : ol.control.defaults({
                    attributionOptions : /** @type {olx.control.AttributionOptions} */
                    ({
                        collapsible : false //左下注脚是否展开
                    })
                }),
                view : new ol.View({
                    center : [ 117, 36.60 ],
                    // center:ol.proj.transform([119, 36.40], 'EPSG:4326', 'EPSG:3857'),
                    zoom : 7,
                    maxZoom : 18,
                    projection : ol.proj.get('EPSG:4326'), //投影坐标系,
                    minZoom : 2
                }),
                target: 'Map'
});

2.地图打点:

图标数组

    var iconStyle1 = new Array(10);
    for (var i = 0; i < 10; i++) {
        iconStyle1[i] = new ol.style.Style({
            image : new ol.style.Icon(/** @type {olx.style.IconOptions} */
            ({
                anchor : [ 0.5, 30 ],
                anchorXUnits : 'fraction',
                anchorYUnits : 'pixels',
                opacity : 1,
                scale : 1,
                src : "images/marker/icon6" + i + ".png"
            })),
            zIndex : 12
        });
    }

点位图层

    /**
     * 实现popup的html元素
     */
    var popupElement = document.getElementById('popup');

    /**
     * 在地图容器中创建一个Overlay
     */

    var popup = new ol.Overlay({
        offset : [ 0, -22 ],
        element : popupElement,
        positioning : 'top-center',
        stopEvent : false
    });
    map.addOverlay(popup);

添加点位

var datas = data.body.data;//点位数据
    for(var i=0;i<datas.length;i++){
        var adPos = datas[i];
        // 获取第一层
        var item = map.getLayers().item(0);
        //坐标信息
        var coordinate;
        if(!adPos.latitude||!adPos.longitude){ //如果经纬度为空,结束循环
                        continue;
        }


        coordinate = {'lat':adPos.latitude,'lon':adPos.longitude};
        //填充点位坐标数据
        //if(item == osmLayer){ //OpenStreetMap 提供的切片数据
        //  coordinate = GPS.gcj_decrypt_exact(Number(adPos.latitude),Number(adPos.longitude));//GPS坐标转换
        //}else{
        //  coordinate = {'lat':adPos.latitude,'lon':adPos.longitude};
        //}

        /*
        * map.getView() 获得视图 
        * getProjection() 获得投影
        * 检查两个投影是否相同,即一个投影中的每个坐标确实代表与另一个投影中的相同坐标相同的地理点。
        */
        if(ol.proj.equivalent(map.getView().getProjection(),ol.proj.get('EPSG:3857'))){
            var bd09 = GPS.bd_encrypt(Number(adPos.latitude),Number(adPos.longitude));
            //var bd09_3857 = GPS.mercator_encrypt(bd09.lat,bd09.lon);
            var bd09_3857 = ol.proj.transform([bd09.lon, bd09.lat], 'EPSG:4326', 'EPSG:3857');//转换源投影到目标投影的坐标。 这会返回一个新的坐标(并且不会修改原始坐标)。
            coordinate = {'lat' : bd09_3857[1], 'lon' : bd09_3857[0]};
        }

        var adPosGis = new ol.Feature({
            geometry : new ol.geom.Point([coordinate.lon,coordinate.lat ]),//设置位置               
            name : 'adPosGis',
            hiddIndex : i
        });

        if(parseInt(adPos.adType)>9){ //点位类型
            adPos.adType="9";
        }

        adPosGis.setStyle(iconStyle1[parseInt(adPos.adType)]);

        vectorSource.addFeature(adPosGis);
    }

点击事件

map.on('click', function(evt) {
        var feature = map.forEachFeatureAtPixel(evt.pixel, function(feature,ayer) {
            return feature;
        })
        if (feature) {
            var geometry = feature.getGeometry();//获取该功能的默认几何体
            var coord = geometry.getCoordinates();//得到坐标
            if ("adPosGis" == feature.get("name")) {
                popup.setPosition(coord);
                showAdvertInfo(feature);
                setSettings();
                $(popupElement).webuiPopover('destroy').webuiPopover(settings);                
                $(popupElement).webuiPopover('show');
            }else {
                var pan = ol.animation.pan({
                    duration : 500,
                    source : (map.getView().getCenter())
                });
            }
        }else{

        }


    });
    var addHTML = document.getElementById("xinxi").innerHTML;
    function showAdvertInfo(feature) {
        var numx = feature.get('hiddIndex');
        var rsjson = datas[numx];
        console.log(rsjson);
        document.getElementById("xinxi").innerHTML = addHTML;   
        $('#xinxi').render(rsjson);
    }


    function setSettings() {    
    settings = {
        trigger : 'click',
        title : '',
        content : document.getElementById("xinxi").innerHTML,
        width : 350,
        multi : true,
        closeable : false,
        cache : false,
        style : '',
        padding : true
    };  
}

3.地图拉框

var draw;
var drawType ;

function addInteraction(type){
    drawType = type;
    drawLayerVector.setVisible(true); //显示画图图层
    map.removeInteraction(draw); //移除绘制图形
    if (drawSourceVector == null) {
        drawSourceVector = new ol.source.Vector({  });
        drawLayerVector.setSource(drawSourceVector); //添加绘制层数据源
    }
    var value = type;
    var geometryFunction, maxPoints;
    if (type === 'Box'){//正方形
        value = 'LineString';
        maxPoints = 2;
        geometryFunction = function (coordinates, geometry) {
            if (!geometry) {
                geometry = new ol.geom.Polygon(null); //多边形
            }
            var start = coordinates[0];
            var end = coordinates[1];
            geometry.setCoordinates([
                [start, [start[0], end[1]], end, [end[0], start[1]], start]
            ]);
            return geometry;
        }
    }

     draw = new ol.interaction.Draw({
        source: drawSourceVector, //绘制层数据源
        type: /** @type {ol.geom.GeometryType} */(value), //几何图形类型
        geometryFunction: geometryFunction, //几何信息变更时调用函数     
        //freehand:true,
        maxPoints: maxPoints //最大点数
     });

     map.addInteraction(draw);
     //添加绘制结束事件监听,在绘制结束后保存信息到数据库
     draw.on('drawend', drawEndCallBack,this);

}

/*
 * 绘制结束事件的回调函数,
 * @param {ol.interaction.DrawEvent} evt 绘制结束事件
 */
 function drawEndCallBack(evt) {  
     vectorSource.clear();//清空矢量标注
     drawSourceVector.clear(); //清空矢量画图层数据源
     currentDrawFeature = evt.feature; //当前绘制的要素
     var geo = currentDrawFeature.getGeometry(); //获取要素的几何信息  
     var coordinates;
     if(drawType=='Box'){
         coordinates = geo.getCoordinates(); //获取几何坐标   
         if(ol.proj.equivalent(map.getView().getProjection(),ol.proj.get('EPSG:3857'))){
             coordinates[0][0] = ol.proj.transform(coordinates[0][0], 'EPSG:3857', 'EPSG:4326');
             coordinates[0][2] = ol.proj.transform(coordinates[0][2], 'EPSG:3857', 'EPSG:4326')
         }
         searchAdvert(coordinates[0][0],coordinates[0][2]);  
         console.log("Box");
         console.log(coordinates[0][0]);
         console.log(coordinates[0][2]);

     }else if(drawType=='Circle'){
         var center = geo.getCenter();
         var radius = geo.getRadius();
         if(ol.proj.equivalent(map.getView().getProjection(),ol.proj.get('EPSG:3857'))){
             center = ol.proj.transform(center, 'EPSG:3857', 'EPSG:4326');
             //radius = radius/111319.49079327358;
             radius = radius/111194.87428468118
         }
         console.log("Circle");
         console.log(ol.proj.METERS_PER_UNIT);
         console.log(map.getView().getProjection().getUnits());
         console.log(map.getView().getProjection().getMetersPerUnit())
         console.log("center:="+center);
         console.log("radius:="+radius);
         searchAdvert('','',center,radius);  
     }else{
         searchAdvert();
     }


     map.removeInteraction(draw); //移除绘图控件


 }

 /*
 *查询清除
 */
 function removeInteraction(){  
    drawSourceVector = null;
    drawLayerVector.setSource(drawSourceVector);//清空绘制图形
    map.removeInteraction(draw); //移除绘图控件
    drawLayerVector.setVisible(false); //不显示画图图层

    vectorSource = new ol.source.Vector({

    });
    advertMarkerLayer.setSource(vectorSource);

    $('#statisticsAdvertGis').hide();//隐藏广告牌分析div
}

/*
*查询
*/
 function searchAdvert(start,end,center,radius){
    vectorSource.clear();//清空矢量标注
    var topleft,lowerright;
    var params = "1=1";
    if(start&&end){
        if(start[0]>end[0]){
            topleft = end;
            lowerright = start;
        }else{
            topleft = start;
            lowerright = end;
        }
        params += "&minx="+topleft[0];
        params += "&maxx="+lowerright[0];
        params += "&miny="+lowerright[1];
        params += "&maxy="+topleft[1];
    }else if(center&&radius){
        params += "&centerx="+center[0];
        params += "&centery="+center[1];
        params += "&radius="+radius;
    }
    console.log("执行");
    console.log(params);

 }

转载自:https://blog.csdn.net/qq_31179919/article/details/79908221

You may also like...