openlayers3加图标定位

        首先想说的是我也是刚刚接触openlayers,因为公司的需求所以开始学习openlayers,刚开始想学openlayers2,但是试过几次发现openlayers2的浏览效果不好,还存在一些浏览卡顿不流畅等问题,于是我转向openlayers3,发现openlayers3确实在效果上好了很多,但是openlayers3在很多语法方面做了较大调整。由于我也是刚刚接触ol3,所以做出的功能也许不多,但后续有新的进展我还会继续跟大家分享,今天就简单介绍一下怎么加载图标,并且定位到图标,还有就是让图标位于屏幕中央以及地图旋转这几个小功能。

       首先废话不多说,先上能够运行的代码。

首先是界面:

<!DOCTYPE html>
<html>
  <head>
    <title>Accessible Map</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" href="http://openlayers.org/en/v3.16.0/css/ol.css" type="text/css">
    <script src="http://openlayers.org/en/v3.16.0/build/ol.js"></script>
   
     <script type="text/javascript" src="js/jquery-1.11.1.js"></script>
    <script src="./js/base.js"></script>
    <script src="./js/ol-deps.js"></script>
    <script src="./js/bing-maps-require.js"></script>
    <style>
      a.skiplink {
        position: absolute;
        clip: rect(1px, 1px, 1px, 1px);
        padding: 0;
        border: 0;
        height: 1px;
        width: 1px;
        overflow: hidden;
      }
      a.skiplink:focus {
        clip: auto;
        height: auto;
        width: auto;
        background-color: #fff;
        padding: 0.3em;
      }
      #map:focus {
        outline: #4A74A8 solid 0.15em;
      }
    </style>
  </head>
  <body>
    <div style="height:100%;width:100%;" id="map" class="map" tabindex="0"></div>
    <select id="select_ditu"><option value="天地图">天地图</option><option value="卫星图">卫星图</option></select>
 
    <input id="flyto" type="button" value="定位到中间"/>
 <script type="text/javascript" src="js/map_add.js"></script>
    <script type="text/javascript">
        $('#select_ditu').change(function(){
            changeLayer($('#select_ditu').val());
        });
    </script>
  </body>
</html>
然后,界面中我引用了map_add.js这个js文件,实现的所有功能全都写在这个文件内,代码如下:

    var attribution = new ol.Attribution({
        html: '? <a href="http://www.chinaonmap.com/map/index.html">���ͼ</a>'
    });
    var coor = ol.proj.transform([116.40969, 39.89945], 'EPSG:4326', 'EPSG:3857');
    var view = new ol.View({
        center: coor,
        zoom: 13
    });
    var layers=[];
    layers.push(
            new ol.layer.Tile({
                source: new ol.source.XYZ({
                    attributions: [attribution],
                    url: "http://t2.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}"
                })
            })
           );
      layers.push(new ol.layer.Tile({
                source: new ol.source.XYZ({
                    url: "http://t2.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}"
                })
            }));
       var styles = [
        'Road',
        'Aerial',
        'AerialWithLabels',
        'collinsBart',
        'ordnanceSurvey'
      ];
      var i, ii;
        for (i = 0, ii = styles.length; i < ii; ++i) {
          layers.push(new ol.layer.Tile({
            visible: false,
            preload: Infinity,
            source: new ol.source.BingMaps({
              key: 'AkGbxXx6tDWf1swIhPJyoAVp06H0s0gDTYslNWWHZ6RoPqMpB9ld5FY1WutX8UoF',
              imagerySet: 'Aerial'
              // use maxZoom 19 to see stretched tiles instead of the BingMaps
              // "no photos at this zoom level" tiles
              // maxZoom: 19
            })
          }));
        }
    var map = new ol.Map({
        layers: layers,
        loadTilesWhileInteracting: true,
        target: 'map',
        view: view
    });
    
    //layers[0].setVisible(false);
    //layers[1].setVisible(false);
    //layers[2].setVisible(true);
     layers[0].setVisible(true);
             layers[1].setVisible(true);
             for (var i=2; i < layers.length; i++) {
               layers[i].setVisible(false);
             };
    
    map.on('pointermove',function(e){
      var coord = e.coordinate;
      var degrees = ol.proj.transform(coord, 'EPSG:3857','EPSG:4326');
      var hdms = ol.coordinate.toStringXY(degrees, 8);
      //var element = overlay.getElement();
      //element.innerHTML = hdms;
      
      $('#longlat').text(hdms);
      //overlay.setPosition(coord);
      //map.addOverlay(overlay);
    });
    
   var addresult=addIcon([0,0]);
    
    map.on('click',function(e){
         var coord = e.coordinate;
         var degrees = ol.proj.transform(coord, 'EPSG:3857','EPSG:4326');
         //alert(degrees[0]);
         $('#text_longtitude').val(degrees[0]);
         $('#text_latitude').val(degrees[1]);
         //addresult.sourceVector.removeFeature(addresult.feature);
         //addresult=addIcon(coord);
         var geometry=new ol.geom.Point(coord);
         addresult.feature.setGeometry(geometry);
         addresult.point=coord;
    });
     
     
     function changeLayer(layer){
         if(layer=="天地图"){
             layers[0].setVisible(true);
             layers[1].setVisible(true);
             for (var i=2; i < layers.length; i++) {
               layers[i].setVisible(false);
             };
         }else if(layer=="卫星图"){
             layers[0].setVisible(false);
             layers[1].setVisible(false);
             for (var i=2; i < layers.length; i++) {
               layers[i].setVisible(true);
             };
         }
     }
     
     function addIcon(coord){
        var iconFeature = new ol.Feature({
        geometry: new ol.geom.Point(coord),
        name: 'Null Island',
        //population: 4000,
        //rainfall: 500
          });
    
          var iconStyle = new ol.style.Style({
            image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
              anchor: [0.5, 1],
              //anchorXUnits: 'fraction',
              //anchorYUnits: 'pixels',
              src: 'imgs/dingwei.png'
            }))
          });
          iconStyle.getImage().setScale(0.3);
          iconFeature.setStyle(iconStyle);
    
          var vectorSource = new ol.source.Vector({
            features: [iconFeature]
          });
    
          var vectorLayer = new ol.layer.Vector({
            source: vectorSource
          });
    
            map.addLayer(vectorLayer);   
            return {feature:iconFeature,layer:vectorLayer,sourceVector:vectorSource,point:coord};
     }
     
        function moveFeature(event) {
        var vectorContext = event.vectorContext;
        var frameState = event.frameState;
        var currentPoint = new ol.geom.Point(routeCoords[index]);
        var feature = new ol.Feature(currentPoint);
        vectorContext.drawFeature(feature, iconFeature);
        // tell OL3 to continue the postcompose animation
        map.render();
      };
      
      
      $(document).ready(function(){
          $('#u52_img').click(function() {
              view.centerOn(addresult.point,[$('map').width(),$('map').height()],[$('map').width()/2,$('map').height()/2]);
          });
      });
        
       $('#flyto').click(function() {
            //flyto(addresult.point);
            rotate(-2);
        });
        
        function flyto(coord){
            var duration = 2000;
            var start = +new Date();
            var pan = ol.animation.pan({
              duration: duration,
              source: /** @type {ol.Coordinate} */ (view.getCenter()),
              start: start
            });
            var bounce = ol.animation.bounce({
              duration: duration,
              resolution: 4 * view.getResolution(),
              start: start
            });
            map.beforeRender(pan, bounce);
            view.setCenter(coord);
        }
        

        function moveto(coord){
              var pan = ol.animation.pan({
              duration: 2000,
              source: /** @type {ol.Coordinate} */ (view.getCenter())
            });
            map.beforeRender(pan);
            view.setCenter(coord);
        }
        
        function rotate(degree){  //degre为pi的倍数,负数顺时针,正数逆时针
            var rotate = ol.animation.rotate({
              duration: 2000,
              rotation: degree* Math.PI
            });
            map.beforeRender(rotate);
        }

以上代码为全部代码,功能上跟大家分不分介绍一下:

我这个程序里面加载了两种地图,一种是天地图,一种是必应的卫星图(因为感觉这个经度较高,也是找了好久才找到)。

加载天地图的主要程序大概如下:

var attribution = new ol.Attribution({
        html: '? <a href="http://www.chinaonmap.com/map/index.html">���ͼ</a>'
    });
    var coor = ol.proj.transform([116.40969, 39.89945], 'EPSG:4326', 'EPSG:3857');
    var view = new ol.View({
        center: coor,
        zoom: 13
    });
    var layers=[];
    layers.push(
            new ol.layer.Tile({
                source: new ol.source.XYZ({
                    attributions: [attribution],
                    url: "http://t2.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}"
                })
            })
           );
      layers.push(new ol.layer.Tile({
                source: new ol.source.XYZ({
                    url: "http://t2.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}"
                })
            }));
然后加载必应地图的图层为:

 var styles = [
        'Road',
        'Aerial',
        'AerialWithLabels',
        'collinsBart',
        'ordnanceSurvey'
      ];
      var i, ii;
        for (i = 0, ii = styles.length; i < ii; ++i) {
          layers.push(new ol.layer.Tile({
            visible: false,
            preload: Infinity,
            source: new ol.source.BingMaps({
              key: 'AkGbxXx6tDWf1swIhPJyoAVp06H0s0gDTYslNWWHZ6RoPqMpB9ld5FY1WutX8UoF',
              imagerySet: 'Aerial'
              // use maxZoom 19 to see stretched tiles instead of the BingMaps
              // "no photos at this zoom level" tiles
              // maxZoom: 19
            })
          }));
        }
然后创建一幅地图:

var map = new ol.Map({
        layers: layers,
        loadTilesWhileInteracting: true,
        target: 'map',
        view: view
    });
接下来,显示鼠标移动点的实时坐标的程序:

 map.on('pointermove',function(e){
      var coord = e.coordinate;
      var degrees = ol.proj.transform(coord, 'EPSG:3857','EPSG:4326');
      var hdms = ol.coordinate.toStringXY(degrees, 8);
      //var element = overlay.getElement();
      //element.innerHTML = hdms;
      
      $('#longlat').text(hdms);
      //overlay.setPosition(coord);
      //map.addOverlay(overlay);
    });
接下来,是添加一个定位点图标的程序:

var addresult=addIcon([0,0]);
     function addIcon(coord){
        var iconFeature = new ol.Feature({
        geometry: new ol.geom.Point(coord),
        name: 'Null Island',
        //population: 4000,
        //rainfall: 500
          });
    
          var iconStyle = new ol.style.Style({
            image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
              anchor: [0.5, 1],
              //anchorXUnits: 'fraction',
              //anchorYUnits: 'pixels',
              src: 'imgs/dingwei.png'
            }))
          });
          iconStyle.getImage().setScale(0.3);
          iconFeature.setStyle(iconStyle);
    
          var vectorSource = new ol.source.Vector({
            features: [iconFeature]
          });
    
          var vectorLayer = new ol.layer.Vector({
            source: vectorSource
          });
    
            map.addLayer(vectorLayer);   
            return {feature:iconFeature,layer:vectorLayer,sourceVector:vectorSource,point:coord};
     }
    
接下来,地图单击事件的时候,让定位点图标移动到鼠标单击点:

map.on('click',function(e){
         var coord = e.coordinate;
         var degrees = ol.proj.transform(coord, 'EPSG:3857','EPSG:4326');
         //alert(degrees[0]);
         $('#text_longtitude').val(degrees[0]);
         $('#text_latitude').val(degrees[1]);
         //addresult.sourceVector.removeFeature(addresult.feature);
         //addresult=addIcon(coord);
         var geometry=new ol.geom.Point(coord);
         addresult.feature.setGeometry(geometry);
         addresult.point=coord;
    });

接下来,改变显示的地图是天地图还是必应卫星图的函数为:

  function changeLayer(layer){
         if(layer=="天地图"){
             layers[0].setVisible(true);
             layers[1].setVisible(true);
             for (var i=2; i < layers.length; i++) {
               layers[i].setVisible(false);
             };
         }else if(layer=="卫星图"){
             layers[0].setVisible(false);
             layers[1].setVisible(false);
             for (var i=2; i < layers.length; i++) {
               layers[i].setVisible(true);
             };
         }
     }

定位到中点的函数(起始还有别的方法):

view.centerOn(addresult.point,[$('map').width(),$('map').height()],[$('map').width()/2,$('map').height()/2]);
后面还有几个函数,我就不依依讲了,function flyto(coord)为飞到相应坐标点,有飞的效果,function moveto(coord)为平移到相应坐标点,function rotate(degree)为使地图转相应的角度,后面这几个函数我的界面里可能没有全部用,读者可以自己试吧。

最后贴上几张图:









  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值