微信公众号如何获取用户所在城市

方法1 : 根据用户访问页面的ip地址解析城市名称
方法2 :根据用户的经纬度坐标解析城市名称

解决方法1:根据IP获取到用户所在城市

/**
     *  获取用户的ip
     */
    function getIp()
    {
        if (getenv("HTTP_CLIENT_IP")) {
            $ip = getenv("HTTP_CLIENT_IP");
        } else if (getenv("HTTP_X_FORWARDED_FOR")) {
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        } else if (getenv("REMOTE_ADDR")) {
            $ip = getenv("REMOTE_ADDR");
        } else {
            $ip = '';
        }
        return $ip;
    }
    // default
    public function indexAction()
    {
        $url = 'http://apia.yikeapi.com/ip/?ip='.$this->getIp().'&appid=43656176&appsecret=I42og6Lm';
        $json = json_decode(file_get_contents($url), true);
        echo '您所在城市名称:' . $json['city'];
    }

有个弊端, 现在很多用户的ip都是 ipv6, 导致普通的ip解析接口识别不到, 无法解析ipv6信息, 不建议继续使用了

解决方法2:通过微信公众号的接口 wx.getLocation 拿到用户的经纬度坐标

前端页面

// 前端页面
wx.ready(function () {
  wx.getLocation({
      type: 'wgs84', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
      success: function (res) {
          var latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90
          var longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180。
          var speed = res.speed; // 速度,以米/每秒计
          var accuracy = res.accuracy; // 位置精度
          console.log(latitude + ' , ' + longitude);
          //更新用户位置
          $.ajax({
              type: 'POST',
              url: '/temp/getCity',
              data: 'lng=' + longitude + '&lat=' + latitude,
              dataType: 'JSON',
              error: function () {
                  layer.msg('网络错误');
              },
              success: function (res) {
                  console.log(res);
              }
          });
      }
  });
});

后端解析LBS接口代码, 可以获取到该坐标的省市区县信息

// default
    public function getCityAction()
    {
        $lng = $_POST['lng'];
        $lat = $_POST['lat'];
        $url = 'http://apia.yikeapi.com/geocode/?appid=43656176&appsecret=I42og6Lm&output=json&location=' . $lng . ',' . $lat;
        $json = json_decode(file_get_contents($url), true);
        echo '您所在城市名称:' . $json['regeocode']['addressComponent']['district'];
    }

附加逆地理编码返回JSON, 接口文档地址:https://yikeapi.com/index/geocode

{
    "errcode":0,
    "errmsg":"success",
    "nums":22,
    "regeocode":{
        "addressComponent":{
            "province":"北京市",
            "city":"北京市",
            "district":"朝阳区",
            "adcode":"110105"
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值