Vue.js实现发布动态选择所在位置

577 阅读1分钟

「这是我参与11月更文挑战的第4天,活动详情查看:2021最后一次更文挑战」。

之前在项目中有个发布动态时设置当前所在位置的功能,该如何实现呢?

首先第一步,需要获取到自己当前的IP地址信息:

可以在入口的index.html中加入这行代码

<script src="http://pv.sohu.com/cityjson?ie=utf-8"></script>

然后在页面加载时执行获取IP的方法:

mounted() { 
  this.getIP()
},
method: {
  getIP(){      
    var cip = returnCitySN["cip"];    
    this.ip = cip  
  },
}

获取到IP之后,需要通过后端接口获取到附近的地址列表,前端方法:

getAdd(){       
  var that = this      
  that.$axios({          
    method: "post",
    url: "/app/news/getadd",
    data: {
      ip: that.ip,
    },        
  }).then(function (res) {
    if (res.data.status == 0) {            
      var ad_info = res.data.result.ad_info            
      that.ad_info = ad_info            
      that.location = ad_info.city + ad_info.district            
      that.lng = res.data.result.location.lng           
      that.lat = res.data.result.location.lat          
    }        
  });   
},

后端以php为例(采用的腾讯地图api,大家可以自行申请key):

$ip = trim($_REQUEST['ip']);        
$res = file_get_contents('https://apis.map.qq.com/ws/location/v1/ip?ip='.$ip.'&key=6IJBZ-MCS6X-YSO4M-ZW7QR-XXXX-XXXX');       
echo $res;

这样就能获取到自己的位置信息了,不过位置只能精确到行政区。

如果还想继续选择其他的地址,比如商场、门店等,就需要对附近的地名进行检索,比如下图

也是很简单,只需把搜索词和上一步获取的经纬度坐标传递给后端即可:

前端方法参考:

getLocation(){
  var that = this
  if(that.keyword.length < 1){
    return
  }
  that.$axios({
    method: "post",
    url: "/api/getlocation",
    data: {
      keyword: that.keyword,
      lng: that.lng,
      lat: that.lat,
    },
  }).then(function (res) {
    if (res.data.status == 0) {
      that.places = res.data.data
    } else {
      this.places = []
    }
  });
},

后端参考:

$keyword = trim($_REQUEST['keyword']);
$lng = trim($_REQUEST['lng']);
$lat = trim($_REQUEST['lat']);
$res = file_get_contents('https://apis.map.qq.com/ws/place/v1/search?boundary=nearby('.$lat.','.$lng.',1000)&page_size=10&page_index=1&key=6IJBZ-MCS6X-YSO4M-ZW7QR-XXXXX-XXXXX&keyword='.$keyword);
echo $res;

这样即可获取到附近相关的位置了。

希望帮助到更多需要的小伙伴,好东西大家一起分享!!!