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