移动端定位

项目中用到了自动定位获取当前的位置的功能,引入高德地图中的定位和使用微信JS-SDK中的定位功能,具体代码以下:javascript

h5定位:

  • 首先安装高德插件AMap
  • 在项目中(咱们使用的是vue框架)create生命周期方法中加载高德地图初始化方法(代码以下)
created() {
    VueAMap.initAMapApiLoader({
      // 高德的key
      key: '本身申请的ID',
      // 插件集合
      plugin: ['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.Scale', 'AMap.OverView', 'AMap.ToolBar', 'AMap.MapType', 'AMap.PolyEditor', 'AMap.Geocoder', 'AMap.Geolocation'],
      // 高德 sdk 版本,默认为 1.4.4
      v: '1.4.4'
    })
  },

复制代码
  • 执行获取当前地址的方法(此方法是异步方法,因此点击获取地址功能按钮时,会有几秒的延时,亲测会有3s-10s的时间),返回值是经纬度
var map = new AMap.Map('container', {
          resizeEnable: true
        })
        const self = this
        AMap.plugin('AMap.Geolocation', function() {
          var geolocation = new AMap.Geolocation({
            enableHighAccuracy: true, // 是否使用高精度定位,默认:true
            timeout: 5000, // 超过10秒后中止定位,默认:5s
            buttonPosition: 'RB', // 定位按钮的停靠位置
            buttonOffset: new AMap.Pixel(10, 20), // 定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)
            zoomToAccuracy: true // 定位成功后是否自动调整地图视野到定位点
          })
          geolocation.getCurrentPosition((status, result) => {
            console.log(status, result)

复制代码
  • 获取到经纬度,根据经纬度转化为具体地址(地址的精确性存在问题,可是能够定位到大概位置)
if (result && result.position) {
              AMap.plugin('AMap.Geocoder', function() {
                var geocoder = new AMap.Geocoder({
                  city: '010'
                })
                geocoder.getAddress([result.position.lng, result.position.lat], function(status, result) {
                  if (status === 'complete' && result.info === 'OK') {
                    self.isLoading = false
                    self.data ={
                      ...self.data,
                      province: result.regeocode.addressComponent.province, 
                      city: result.regeocode.addressComponent.city,
                      county: result.regeocode.addressComponent.district,
                      area_code: result.regeocode.addressComponent.adcode
                    }
                  }
                })
              })

复制代码

微信定位

  • 首先判断是否在微信环境中而后执行以下代码
wx.getLocation({
          type: 'gcj02',
          success: (res) => {
            if (res.longitude && res.latitude) {
              AMap.plugin('AMap.Geocoder', function() {
                var geocoder = new AMap.Geocoder({
                  city: '010'
                })
                geocoder.getAddress([res.longitude, res.latitude], function(status, result) {


复制代码

返回的longitude和latitude就是经纬度,而后调用高德地图经纬度转化为具体的方法。vue

第一次写,没有经验。但愿能够你们不吝赐教,谢谢!java

相关文章
相关标签/搜索