openlayers官方教程(三)Basics——Zooming to your location

Zooming to your location

浏览器提供了获取用户当前位置的API,我们可以利用这个来定位当前用户所在。

Application changes

首先,将map赋值到一个常量,就可以从其他组件中获取map

const map = new Map({

在main.js中增加如下代码,来实现定位的功能

navigator.geolocation.getCurrentPosition(function(pos) {
  const coords = fromLonLat([pos.coords.longitude, pos.coords.latitude]);
  map.getView().animate({center: coords, zoom: 10});
});

以上代码用到fromLonLat()函数,这个函数时将经纬度坐标转到地图默认坐标系统EPSG:3857,需要导入此函数。

import {fromLonLat} from 'ol/proj';

View the result

可以在 http://localhost:3000/中查看效果

猜你喜欢

转载自blog.csdn.net/u011435933/article/details/80439884
今日推荐