前端定位方法

前端定位方法

1. H5 定位

window.navigator.geolocation.getCurrentPosition(
  function(position) {
    console.log(position.coords); // 坐标
    console.log("经度", position.coords.longitude); // 经度
    console.log("纬度", position.coords.latitude); // 纬度
  },
  function() {
    console.log("定位失败");
  },
  { timeout: 5000 }
);

2. 微信 SDK 定位

  • 仅适用: 微信客户端 H5
<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
wx.config({
  debug: false, // 开启调试模式
  appId: data.appId, // 必填,企业号的唯一标识,此处填写企业号corpid
  timestamp: data.timestamp, // 必填,生成签名的时间戳
  nonceStr: data.nonceStr, // 必填,生成签名的随机串
  signature: data.signature, // 必填,签名,见附录1
  jsApiList: ["getLocation"] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
});

wx.ready(function() {
  // 获取经纬度
  wx.getLocation({
    type: "wgs84", // 坐标系
    success: function(res) {
      console.log(res.latitude); // 纬度
      console.log(res.longitude); // 经度
    },
    cancel: function(res) {
      alert(
        "定位授权失败,请进入【设置】中打开定位服务,并允许微信使用定位服务"
      );
    },
    fail: function(error) {
      alert("定位失败!" + error.errMsg);
    }
  });
});

3. 支付宝 SDK

  • 仅适用: 支付宝客户端 H5
function ready(callback) {
  // 如果jsbridge已经注入则直接调用
  if (window.AlipayJSBridge) {
    callback && callback();
  } else {
    // 如果没有注入则监听注入的事件
    document.addEventListener("AlipayJSBridgeReady", callback, false);
  }
}

ready(function() {
  AlipayJSBridge.call("getCurrentLocation", { bizType: "didi" }, function(
    result
  ) {
    if (result.error) {
      console.log("获取定位失败");
      return;
    }
    console.log("latitude", result.latitude); // 纬度
    console.log("longitude", result.longitude); // 经度
  });
});

4. 高德定位

<script type="text/javascript" src="http:// webapi.amap.com/maps?v=1.4.1&key=你的key"></script>
var map = new AMap.Map("iCenter");
map.plugin("AMap.Geolocation", function() {
  geolocation = new AMap.Geolocation({
    enableHighAccuracy: true, // 是否使用高精度定位,默认:true
    timeout: 10000, // 超过10秒后停止定位,默认:无穷大
    maximumAge: 0, // 定位结果缓存0毫秒,默认:0
    convert: true // 自动偏移坐标,偏移后的坐标为高德坐标,默认:true
  });
  geolocation.getCurrentPosition();
  AMap.event.addListener(geolocation, "complete", onComplete); // 返回定位信息
  AMap.event.addListener(geolocation, "error", onError); // 返回定位出错信息
});

function onComplete(data) {
  console.log("经度" + data.position.getLng());
  console.log("纬度" + data.position.getLat());
}
function onError(err) {
  console.log("err", err);
}