获取定位及附近位置 , 输入框搜索附近位置(三种方法)

一 , 前两种方法, 服务器都必须升级到https ,http无法获取定位, 但是http可以在localhost本地浏览器里获取到 (谷歌浏览器localhost也不行 , 火狐浏览器中可以)

二 , 第三种方法是用微信的api , wx.getLocation , 在微信平台中实现 , 比如微信小程序, 公众号 , 企业微信里的H5页面 , 这个方法电脑上无法获取定位 , 只能在手机微信平台上

研究这个定位已经研究几天了 , 百度都翻烂了 , 最后还是没搞出来http怎么获取定位, 如果有知道的大神可以指教一下

先看结果 , 有两个功能

一 :  获取当前定位以及附近位置

二 :  一个输入框 , 可以输入搜索附近位置

三 , 用三种方法实现 , 高德api直接获取 , 浏览器api获取经纬度再用高德api逆地址解析出具体位置 , wx.getLocation获取经纬度再用高德api逆地址解析出具体位置 (下面三个截图对应三种方法)

搜索附近位置

上代码

一 , index.html中引入高德jsdk , key是你自己在高德开放平台申请的 , 要申请web端的key 

高德开放平台网站 : https://lbs.amap.com/

怎么申请  ?  看这里 == >  申请高德地图开发者key_青梅煮酒-CSDN博客_高德地图注册成为开发者

  <!-- 引入高德地图jsdk ,web端的key-->
  <script src="https://webapi.amap.com/maps?v=1.4.15&key=4e3c7848a50dda0dbe3b30234b040377"></script>

二 , 新建一个vue页面 ,把下面代码全部贴过去 , 打开就是我上面截图的效果 , 每行代码都注释的很清楚

<template>
  <div>
    <van-search v-model="value" placeholder="搜索附近位置" show-action @search="onSearch" @cancel="onCancel" @clear="onCancel" />
    <div class="searchResult" :style='Style'>
      <ul>
        <li v-for="(item,index) in searchList" :key="index">
          {{item.name}} <br>
          {{item.address}}
        </li>
      </ul>

    </div>
    <button @click="getLocation">高德api获取定位</button>

    <button @click="getPosition">浏览器api获取定位</button>

    <button @click="getWXPosition">微信api获取定位</button>


    <div>当前位置 : {{dz}}</div>

    <div> 纬度 : {{latitude}}</div>

    <div class="jd">经度 :{{longitude}} </div>

    <h3>附近:</h3>
    <ul>
      <li v-for="(item,index) in list" :key="index">
        {{item.name}} <br>
        {{item.address}}
      </li>
    </ul>

  </div>
</template>

<script>
  export default {
    name: '',
    data() {
      return {
        // 当前位置
        dz: "",
        // 纬度
        latitude: "",
        // 经度
        longitude: '',
        // 附近
        list: "",
        // 城市名
        city: "",
        // 搜索地点
        searchList: "",
        // 搜索结果显示/隐藏
        Style: {
          display: "none"
        },
        // 搜索关键字
        value: ""
      }
    },
    methods: {
      // 高德api获取定位(可直接获取到具体位置)
      getLocation() {
        var that = this
        let geolocation
        AMap.plugin('AMap.Geolocation', function () {
          geolocation = new AMap.Geolocation();
          geolocation.getCurrentPosition((status, result) => {
            if (status == 'complete') {
              that.onComplete(result)
            } else {
              that.onError(result)
            }
          });
        })
      },
      //定位成功
      onComplete(data) {
        console.log(data);
        // 当前地址
        this.dz = data.formattedAddress;
        // 经纬度
        this.latitude = data.position.lat;
        this.longitude = data.position.lng;
        console.log(this.latitude, this.longitude);
        alert(`纬度是 ${this.latitude}`);
        alert(`经度是 ${this.longitude}`);
        alert(this.dz);
        // 调用查询周边的方法, 传经纬度 , 城市名
        this.aMapSearchNearBy(`${this.longitude},${this.latitude}`, data.addressComponent.city)
      },
      //定位失败
      onError(data) {
        console.log("定位失败:" + data.message);
        alert("定位失败:" + data.message);
      },




      // 浏览器自带api获取经纬度(只能获取经纬度再用高德api解析出位置)
      getPosition() {
        if (navigator.geolocation) {
          alert('支持定位')
          navigator.geolocation.getCurrentPosition(this.showPosition, this.showError);
        } else {
          alert("浏览器不支持地理定位");
        }
      },
      // 获取经纬度成功
      async showPosition(position) {
        console.log(position);
        this.latitude = position.coords.latitude; //纬度
        this.longitude = position.coords.longitude; //经度
        console.log(this.latitude, this.longitude);
        alert(`纬度是 ${this.latitude}`);
        alert(`经度是 ${this.longitude}`);
        // 根据经纬度解析成位置信息
        let geocoder
        AMap.plugin("AMap.Geocoder", function () {
          geocoder = new AMap.Geocoder();
        })
        geocoder.getAddress(`${this.longitude},${this.latitude}`, (status, {
          regeocode
        }) => {
          console.log(regeocode);
          if (status === 'complete' && regeocode) {
            // formattedAddress即经纬度转换后的位置名称
            this.dz = regeocode.formattedAddress
            this.city = regeocode.addressComponent.city
            console.log(this.dz, this.city);
            alert(this.dz, this.city);
            // 调用查询周边的方法, 传经纬度 , 城市名
            this.aMapSearchNearBy(`${this.longitude},${this.latitude}`, this.city)
          } else {
            // 失败回调 status 统一返回1
            switch (originMessage) {
              case 'Timeout expired':
                // 超时
                break;
              case 'User denied Geolocation':
                // 拒绝授权
                break;
              case 'error Network location provider at \'https://www.googleapis.com/\' : No response received.':
                // 不支持定位,定位不可用的浏览器
                break;
              default:
                // 其他错误
                return;
            }
          }
        })
      },
      // 获取经纬度失败
      showError(error) {
        switch (error.code) {
          case error.PERMISSION_DENIED:
            alert("定位失败,用户拒绝请求地理定位");
            break;
          case error.POSITION_UNAVAILABLE:
            alert("定位失败,位置信息是不可用");
            break;
          case error.TIMEOUT:
            alert("定位失败,请求获取用户位置超时");
            break;
          case error.UNKNOWN_ERROR:
            alert("定位失败,定位系统失效");
            break;
        }
      },




      // 微信api获取经纬度
      getWXPosition() {
        alert('获取当前位置')
        wx.getLocation({
          type: 'gcj02',
          success: res => {
            console.log('获取经纬度成功');
            alert('获取经纬度成功');
            this.latitude = res.latitude.toFixed(6);
            this.longitude = res.longitude.toFixed(6);
            console.log(this.latitude, this.longitude);
            alert(`纬度是 ${this.latitude}`);
            alert(`经度是 ${this.longitude}`);
            // 根据经纬度解析成位置信息
            let geocoder;
            AMap.plugin('AMap.Geocoder', function () {
              geocoder = new AMap.Geocoder();
            });

            geocoder.getAddress(`${this.longitude},${this.latitude}`, (status, {
              regeocode
            }) => {
              console.log(regeocode);
              if (status === 'complete' && regeocode) {
                // formattedAddress即经纬度转换后的位置名称
                this.dz = regeocode.formattedAddress;
                this.city = regeocode.addressComponent.city;
                console.log(this.dz, this.city);
                alert(`当前位置是${this.dz}`);
                alert(`当前城市是${this.city}`);
                // 调用查询周边的方法, 传经纬度 , 城市名
                this.aMapSearchNearBy(`${this.longitude},${this.latitude}`, this.city);
              } else {
                // 失败回调 status 统一返回1
                switch (originMessage) {
                  case 'Timeout expired':
                    // 超时
                    break;
                  case 'User denied Geolocation':
                    // 拒绝授权
                    break;
                  case "error Network location provider at 'https://www.googleapis.com/' : No response received.":
                    // 不支持定位,定位不可用的浏览器
                    break;
                  default:
                    // 其他错误
                    return;
                }
              }
            });
          },
          fail: res => {
            console.log('获取经纬度失败');
            alert('获取经纬度失败');
            alert(res.errMsg);
          }
        });
      },



      // 查询附近地点的方法
      aMapSearchNearBy(centerPoint, city) {
        var that = this;
        let placeSearch
        AMap.service(["AMap.PlaceSearch"], function () {
          placeSearch = new AMap.PlaceSearch({
            pageSize: 20,
            pageIndex: 1,
            city: city
          });
          placeSearch.searchNearBy('', centerPoint, 1000, function (status, result) {
            console.log(result);
            if (result.info === 'OK') {
              var locationList = result.poiList.pois;
              that.list = locationList
            } else {
              alert('获取位置信息失败!请重试');
            }
          });
        });
      },



      // 输入框搜索时
      onSearch(val) {
        var that = this
        let placeSearch
        AMap.plugin('AMap.PlaceSearch', function () {
          placeSearch = new AMap.PlaceSearch({
            pageSize: 20
          })
          placeSearch.search(`${val}`, (status, result) => {
            console.log(result);
            that.searchList = result.poiList.pois
            console.log(that.searchList);
            // 显示搜索结果
            that.Style.display = "block"
          })
        })
      },


      // 取消搜索时
      onCancel() {
        this.Style.display = "none"
      },
    }
  }

</script>

<style lang="scss" scoped>
  button {
    width: 300px;
    height: 100px;

  }

  li {
    margin: 20px;
  }

  div {
    margin: 10px;
  }

  .jd {
    margin-bottom: 20px;
  }

  button {
    margin-top: 10px;
  }

  .searchResult {
    position: absolute;
    width: 100%;
    background: #eee;
    left: 0
  }

</style>

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以通过监听输入框的 focus 和 blur 事件来实现获取焦点显示、失去焦点隐藏的效果,具体代码如下: ```html <!DOCTYPE html> <html> <head> <title>百度输入框</title> <style> #search-box { position: relative; width: 400px; height: 30px; margin: 0 auto; margin-top: 100px; } #search-input { width: 100%; height: 100%; padding: 0 10px; font-size: 16px; border: 1px solid #ccc; border-radius: 15px; outline: none; box-sizing: border-box; } #search-suggest { position: absolute; top: 30px; left: 0; width: 400px; max-height: 200px; overflow: auto; box-sizing: border-box; border: 1px solid #ccc; border-radius: 5px; background-color: #fff; display: none; } #search-suggest ul { list-style: none; margin: 0; padding: 0; } #search-suggest li { height: 30px; line-height: 30px; padding: 0 10px; cursor: pointer; } #search-suggest li:hover { background-color: #f5f5f5; } </style> </head> <body> <div id="search-box"> <input type="text" id="search-input" placeholder="输入搜索内容"> <div id="search-suggest"></div> </div> <script> var searchInput = document.getElementById('search-input'); var searchSuggest = document.getElementById('search-suggest'); searchInput.addEventListener('focus', function() { searchSuggest.style.display = 'block'; }); searchInput.addEventListener('blur', function() { searchSuggest.style.display = 'none'; }); </script> </body> </html> ``` 通过监听输入框的 focus 和 blur 事件,当输入框获取焦点时,显示搜索建议框,当输入框失去焦点时,隐藏搜索建议框。搜索建议框使用绝对定位实现,并设置了最大高度和滚动条。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值