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);

 }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章