首页 > 其他分享 >微信公众号如何获取用户所在城市

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

时间:2022-11-14 17:16:36浏览次数:70  
标签:function 所在城市 ip 用户 res getenv 获取 json 微信

方法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"
        }
    }
}

标签:function,所在城市,ip,用户,res,getenv,获取,json,微信
From: https://www.cnblogs.com/ccwangjin/p/16889555.html

相关文章