openlayers with Google maps 简单教程

来源:互联网 发布:软件项目计划安排 编辑:程序博客网 时间:2024/06/05 05:07

转自:http://www.07net01.com/2015/07/867199.html

what is openlayer

openlayers是一个高性能、功能全面的地图库。有以下特性:

  1. 支持各种格式的tiled layers数据
  2. 使用canvas的高性能vector layer
  3. 细粒度丰富的交互操作
  4. 支持commanjs风格
  5. 开源免费

why use it

一般来说google map api就满足需求了,但是当需要在地图上绘制大量节点时,使用svg来显示部件就会出现很严重的性能问题,一般情况下google maps等的编辑操作也不够流畅。而openlayers使用canvas作为矢量层,大量的点线面信息对于canvas的影响是较小的,而且canvas的交互也更加流畅。

why write this article

  1. 与高德地图、google maps、百度地图等国内常用地图没有很方便的接口
  2. 大版本更新后官方文档不全面而且不够清晰,没有guild
  3. 而且网上简明详细的教程很少

针对以上几点,觉得自己的小经验会对大家有所帮助,可以少走些弯路,也是对自己这几天工作的一个总结。

a simple example(step by step)

下面通过一个简单地小例子介绍openlayers的一些基本用法,以及我觉得重要的地方。

需求

需要使用google map或者高德地图作为底图,在地图上绘制一个矩形,实现矩形的编辑并且能够得到矩形被修改之后的回调函数。大概会涉及到这些技术点:

  1. 如何与google map等地图组合使用
  2. 知道坐标数组或者某格式的geo数据,如何在地图上添加feature
  3. 完成feature的修改
  4. 得到feature修改后的回调方法

初始化地图

我们希望openlayer能和google map等组合使用,但是由于google等地图厂商不愿意向openlayer“妥协”,因此现在无法直接使用Tiled Layers,但我们可以将openlayer与地图api组合起来使用。

只使用地图的底图,在底图上覆盖一层 openlayer 的 canvas 层来显示数据并拦截与底图之间的交互,通过地图的 api 来重设状态。
此方案还有以下优点:

  1. 解决了页面节点过多之后的性能问题
  2. 底图可以被抽象出去,能够在不影响交互逻辑的基础上更换底图。

代码如下:

<!DOCTYPE html><html><head>  <title>Snap interaction example</title>  <script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ol3/3.6.0/ol.css" type="text/css">  <script src="https://cdnjs.cloudflare.com/ajax/libs/ol3/3.6.0/ol.js"></script>  <script src="https://maps.googleapis.com/maps/api/js"></script>  <style type="text/css">    div.fill {      width: 100%;      height: 100%;    }    .map {      width: 800px;      height: 400px;    }  </style></head><body><div class="container-fluid">  <div class="row-fluid">    <div class="span12">      <div id="map" class="map">        <!-- gmap用于加载google maps, olmap用于加载openlayer canvas。        目标是加载完毕之后olmap覆盖与gmap之上并且拦截交互操作。        开始时放在同一层的好处是都能根据父节点来设置长宽。也可以在js中动态生成div,渲染后插入 -->        <div id="gmap" class="fill"></div>        <div id="olmap" class="fill"></div>      </div>    </div>  </div></div><script type="application/Javascript">  // 加载google map并禁用地图的交互操作  var gmap = new google.maps.Map(document.getElementById('gmap'), {    disableDefaultUI: true,    keyboardShortcuts: false,    draggable: false,    disableDoubleClickZoom: true,    scrollwheel: false,    streetViewControl: false  });  // ol.View 是openlayers用于控制地图的 坐标系标准 zoom center rotate等操作的对象,在实例化map时候需要使用  var view = new ol.View({    // make sure the view doesn't go beyond the 22 zoom levels of Google Maps    maxZoom: 21,    projection: 'EPSG:4326' // 设置为标准经纬度的坐标标准,十分重要! 默认是'EPSG:3857'  });  // view 拖动时触发事件,根据当前的坐标转化为经纬度,调用谷歌地图setCenter方法同步地图位置  view.on('change:center', function () {    var center = view.getCenter();    gmap.setCenter(new google.maps.LatLng(center[1], center[0])); // 注意顺序  });  // 同上,更改焦距时触发的时间  view.on('change:resolution', function () {    gmap.setZoom(view.getZoom());  });  // ol.source.Vector 作为 ol.layer.Vector的数据集,增删改feature的方法由source提供  var vectorSource = new ol.source.Vector();  var vector = new ol.layer.Vector({    source: vectorSource  });  var olMapDiv = document.getElementById('olmap');  var map = new ol.Map({    layers: [vector], // 所使用的图层    // 禁用掉默认的拖动、旋转等交互    interactions: ol.interaction.defaults({      altShiftDragRotate: false,      dragPan: false,      rotate: false    }).extend([new ol.interaction.DragPan({kinetic: null})]),    target: olMapDiv,    view: view  // 这里可以使用 new ol.View({options}) 但是在这里需要通过手动设置来触发google maps调节到正确地zoom与center  });  view.setCenter([10.689697265625, -25.0927734375]); // 如果未设置view的坐标标准,这里千万要注意不要直接写经纬度  view.setZoom(6);  // 设置缩放等级    // 将openlayers容器放置到google地图容器中  olMapDiv.parentNode.removeChild(olMapDiv);  gmap.controls[google.maps.ControlPosition.TOP_LEFT].push(olMapDiv);</script></body></html>

有了这段代码应该就有了一个可以拖动缩放的地图了。

添加feature

当然光有一个地图是不行的,如果需要往地图上面添加feature怎么办呢?大致有以下两种场景:

  1. 提供整个地图的信息描述数据,比如geoJson,WKT或者自定义的数据结构等,需要解析整个数据并批量显示在地图上。
  2. 拿到某个feature的坐标数据,需要添加到地图上,并实现特异化的控制。

批量添加数据

先上代码

/**   * 将geoJson字符串解析后添加到地图中   * @param vectorSource {ol.source.Vector} 需要添加feature的矢量层数据对象   * @param data {string} geoJson字符串   */  function addFeatures(vectorSource, data){ vectorSource.addFeatures(ol.format.GeoJSON.readFeatures(data, {      // 数据的坐标code      dataProjection: 'EPSG:3857',      // 地图view使用的坐标code      featureProjection: 'EPSG:4326'    }));  }

ol.format下有很多种数据类型,选择匹配的数据格式。
比如WKT使用ol.format.WKT.readFeature

readFeature返回的是ol.Feature的数组,可以通过遍历其来获得feature对象,从而按需求修改或者挂载监听事件。

添加单个feature

如果现有的数据是geoJson等标准格式的数据,可以通过ol.format中的类进行转换。如果有需求则使用ol.proj.transform进行坐标系转换。

// 返回单个feature对象var feature = ol.format.GeoJSON.readFeature(data)// 添加到sourcevectorSource.addFeature(feature);

如果拿到的是经纬度信息,添加一个polygon

// data 是一个coordinates的二维数组 需要注意var feature = new ol.feature(new ol.geom.Polygon(data));

修改feature

介绍如何修改feature以及挂载监听事件。

初始化修改添加、修改交互

// 声明选择交互 var select = new ol.interaction.Select({      // 根据 feature editable 选项来判断是否可以选中      filter: function(feature) {        if (_this._featureMap[feature.getId()].editable) {          return true;        }      }    });// 得到被选中元件的对象var selected = select.getFeatures();// 声明修改交互,可以修改被选中的featurevar modify = new ol.interaction.Modify({  features: selected});// 当新元件被选中时触发selected.on('add', event => {  var feature = event.element})// 当元件被取消选中时触发,一般把元件的修改回调放在这    selected.on('remove', evt => {      var feature = evt.element;      var fid = feature.getId();      // 判断元件是否被修改还是需要feature的change事件      console.log(fid);    });// 在interactions中添加this._map = new ol.Map({      layers: [vector],      interactions: ol.interaction.defaults({        altShiftDragRotate: false,        dragPan: false,        rotate: false      }).extend([new ol.interaction.DragPan({kinetic: null}), select, modify]),      target: $olMapDiv,      view: this._view    });

一般来说如果需要后续对feature进行操作,可以使用getId方法拿到featureid,可以通过setId来设置自己想要的id,否则会自动生成。 将id存在常驻的对象中供以后使用。

假设拿到ol.Feature对象 feature

feature.on('change:geometry', function(e){  var feature = e.element;  // do what you want  比如标记元件已被修改})

需要注意的是这个onChange事件在修改的过程中会不断地触发,如果需要的是修改完成之后的回调,需要使用selectremove事件。

select.getFeatures().on('remove', function(e){})

修改feature对象

设置id

feature.setId(id)

得到geometry对象

var geometry = feature.getGeometry();// 通过调用geometry类的方法修改元件坐标

feature to string

var format = new ol.format.GeoJSON();format.writeFeature(feature);

需要注意的地方

  • openlayers默认的坐标系是'EPSG:3857',标准经纬度坐标系是'EPSG:4326'
  • 看openlayer文档最重要的技巧是注意类型
  • geometry接受的coordinates其实是一个三维数组,一定要注意

常用操作

坐标系转换

根据当前坐标系与目标坐标系进行转换。

ol.proj.transform(coordinate, source, destination)
coordinate 在文档中得类型是 Coordinate其实就是一个有横纵坐标组成的数组,因此一定要注意官方文档中得数据类型。
source 当前坐标编码 string类型
destination 目标坐标编码 string类型

从经纬度转化到指定坐标系

ol.proj.fromLonLat(coordinate, opt_projection)
opt_projection 目标坐标编码 string类型

从某坐标转经纬度

ol.proj.toLonLat(coordinate, opt_projection)

数据格式化

ol.format






0 0
原创粉丝点击