整个是应用在vue 中 ,在uniapp的webview中镶嵌,
webview的src必须是https,否则谷歌api无法获取gps信息
navigator.geolocation.getCurrentPosition()方法
第一个参数是获取成功的callback函数,
第二个参数是获取失败时调用的函数
第三个是options,可选参数有
1、enableHighAcuracy — 布尔值: 表示是否启用高精确度模式,如果启用这种模式,浏览器在获取位置信息时可能需要耗费更多的时间。
2、timeout — 整数: 表示浏览需要在指定的时间内获取位置信息,否则触发errorCallback。
3、maximumAge — 整数/常量: 表示浏览器重新获取位置信息的时间间隔。
监听的方法navigator.geolocation.watchPosition同上,他会返回一个id
销毁监听
navigator.geolocation.clearWatch()传参监听的id,
navigator.geolocation.clearWatch(this.watchPositionId);
getGDM() {
let that = this;
//初始获取
navigator.geolocation.getCurrentPosition(
(position) => {
// 获取Coordinates对象,该对象里包含了详细的地理位置信息
var coords = position.coords;
// 输出地理位置信息
that.setMarker(coords.longitude, coords.latitude);
that.center = [coords.longitude, coords.latitude];
},
(error) => {
// 为不同错误代码定义错误提示
var errMsg = {
1: "用户拒绝了位置服务",
2: "无法获取地址位置信息",
3: "获取地理位置信息超时",
};
// 弹出错误提示
alert(errMsg[error.code]);
},
{
enableHighAccuracy: true, //开启高精度
maximumAge: 1000, //浏览器重新计算位置的时间间隔
}
);
//持续监听gps位置变化
this.watchPositionId = navigator.geolocation.watchPosition(
(position) => {
// 获取Coordinates对象,该对象里包含了详细的地理位置信息
var coords = position.coords;
// 输出地理位置信息
that.setMarker(coords.longitude, coords.latitude);
},
(error) => {
// 为不同错误代码定义错误提示
var errMsg = {
1: "用户拒绝了位置服务",
2: "无法获取地址位置信息",
3: "获取地理位置信息超时",
};
// 弹出错误提示
alert(errMsg[error.code]);
},
{
enableHighAccuracy: true, //开启高精度
maximumAge: 500, //浏览器重新计算位置的时间间隔
})
},
setMarker(x, y) {
if (x && y && this.positionMarker==null) {
//创建一个覆盖物
let positionMarker = new Overlay({
element: document.getElementById("marker"),
positioning: "center-center",
id:1
});
positionMarker.setPosition([x, y]); //设置overlay的位置
this.map.addOverlay(positionMarker);
//设置地图中心点
this.map.getView().animate({
center: [x, y],
duration: 10,
});
this.positionMarker = positionMarker;
}else{
//若不是第一获取,则仅改变覆盖物overlay的位置,不在重新创建
this.map.getOverlayById("1").setPosition([x, y])
}
},
如果是在前端页面上直接使用,则可以使用
<script type="text/javascript" src='http://maps.google.com/maps/api/js?sensor=false'></script>
进行调用navigator.geolocation的api,也不需要进行https的访问,http就可以了
参考:
https://openlayers.org/
https://blog.csdn.net/iteye_5722/article/details/82681308