OpenLayers Workshop(三)Mobile Maps and Sensors

Geolocation

Show the user’s location 显示用户位置

浏览器的Geolocation API可以让我们获取设备的GPS位置(或者不使用GPS,只获取大致位置).在OpenLayers中,我们可以将位置信息在地图上用一个图标来可视化显示.此外我们还能在展示显示位置的精度范围.我们还能天机一个按钮来讲目前的位置居中.

首先要在main.js中添加vector source的引用:

import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';

然后我们需要创建一个vector source以显示GPS位置信息,将source加入到layer中,并将layer添加到map中.

const source = new VectorSource();
const layer = new VectorLayer({
  source: source
});
map.addLayer(layer);

引入可视化GPS位置信息的功能和几何组件:

import Feature from 'ol/Feature';
import {circular} from 'ol/geom/Polygon';
import Point from 'ol/geom/Point';

有了这些东西后,我们就能使用浏览器的Geolocation API来获取位置信息和精确度.代码如下:

navigator.geolocation.watchPosition(function(pos) {
  const coords = [pos.coords.longitude, pos.coords.latitude];
  const accuracy = circular(coords, pos.coords.accuracy);
  source.clear(true);
  source.addFeatures([
    new Feature(accuracy.transform('EPSG:4326', map.getView().getProjection())),
    new Feature(new Point(fromLonLat(coords)))
  ]);
}, function(error) {
  alert(`ERROR: ${error.message}`);
}, {
  enableHighAccuracy: true
});

这个代码使用函数watchPosition()来对用户的位置进行更新(只要位置更新就会调用个函数).这个函数使用经纬度和准确性,并提由此创建两个特征:具有精度半径的圆形多边形和一个具有位置信息的点.这些特征都将从地理位置坐标转换为视图投影.

此外,我们还增加了一个错误处理以提醒用户位置信息不可用,并配置Geolocation以开启高精度功能(开启后将会请求获取精确的GPS位置信息,如果不开启,将会默认获取一个大概的位置).

此时,这个地图已经能够展示用户的位置了.不过我们还需要增加一个按钮来实现居中功能.最简单的方法是使用OpenLayers的Control,以下是它的引用:

import Control from 'ol/control/Control';

为这个Control创建一个html标签,并为其注册一个监听器,这个监听器将通过0.5的动画将地图拟合到包含为支点和精度多边形的源范围.

const locate = document.createElement('div');
locate.className = 'ol-control ol-unselectable locate';
locate.innerHTML = '<button title="Locate me">◎</button>';
locate.addEventListener('click', function() {
  if (!source.isEmpty()) {
    map.getView().fit(source.getExtent(), {
      maxZoom: 18,
      duration: 500
    });
  }
});
map.addControl(new Control({
  element: locate
}));

在index.html中加入css样式来美化按钮的位置:

.locate {
  top: 6em;
  left: .5em;
}

发表评论