Home > Backend Development > PHP Tutorial > PHP WeChat development returns nearby information based on user reply keyword location_php example

PHP WeChat development returns nearby information based on user reply keyword location_php example

WBOY
Release: 2016-07-06 13:32:16
Original
808 people have browsed it

After users follow the WeChat official account, they can reply to the user's geographical location (Tencent Map) to the official account, extract the latitude and longitude of the location information, and convert it into Baidu's latitude and longitude. Then based on the latitude and longitude, the API of Baidu Map is called to return information such as "restaurants" and "hotels" (can be customized) within a radius of 2KM. When calling Baidu's API, you need to obtain apiKEY. If not, please go to the Baidu Developer Center to register and apply.

First, test the data returned by the interface with a set of latitude and longitude:

<&#63;php

/**根据一组经纬度查找附近2公里以内的关键字**/

header('Content-type:text/html;charset=utf-8');

//--------第一步:转换经纬度----
//参考链接:http://developer.baidu.com/map/index.php&#63;title=webapi/guide/changeposition

$Location_X = 23.134521;
$Location_Y = 113.358803;

$url = "http://api.map.baidu.com/geoconv/v1/&#63;coords=$Location_X,$Location_Y&from=3&to=5&ak=这里填写你的apikey";

$res = file_get_contents($url);
$res = json_decode($res, true);

//用户发送腾讯的soso地图位置信息经过转换之后,得到百度地图的经纬度
$x = $res['result'][0]['x'];
$y = $res['result'][0]['y'];

//---------第二步:根据经纬度和关键词获得附近的信息----------
//参考链接:http://developer.baidu.com/map/index.php&#63;title=webapi/guide/webservice-placeapi
$url = "http://api.map.baidu.com/place/v2/search&#63;ak=这里填写你的apikey&output=json&query=" . urlencode("饭店") . "&page_size=10&page_num=0&scope=2&location=$x,$y&radius=2000";
$res = file_get_contents($url);
$res = json_decode($res, true);

// echo "<pre class="brush:php;toolbar:false">";
// print_r($res);
// echo "
"; //提取所需的信息 foreach($res['results'] as $k=>$v){ $arr[$k]['name'] = $v['name']; $arr[$k]['address'] = $v['address']; $arr[$k]['img_url'] = 'http://misakaqnxt-public.stor.sinaapp.com/click.png'; $arr[$k]['detail_url'] = isset($v['detail_info']['detail_url'])?$v['detail_info']['detail_url']:''; } echo "
";
 print_r($arr);
 echo "
";
Copy after login

Returned data

If you filled in the correct apikey, the above data should be returned. Next: In the WeChat interface platform code (a PHP script placed in your public domain name space), determine the message type, obtain the latitude and longitude, call the Baidu Map API, and splice the XML to return it. Since there is no thumbnail image of "restaurant" in the data returned by Baidu API, I used a picture from my own website.
In order to allow users to customize the search for nearby "restaurants"
Or "hotel" and other information, you can first ask the user to reply "Looking for XX", then extract XX and put it in the session, and then take out the session when the user replies with the geographical location. But after I set up the session, I couldn't remove the session. So I use Sina Cloud's KVDB service here. Of course, you can also use caching methods such as memcache or Redis.

$which = mb_substr($keyword, 0, 2, 'UTF-8');

elseif($which == "寻找"){

        $find = str_replace($which, "", $keyword);

        //调用新浪云的KVDB服务
        $kv = new SaeKV();
        $kv->init();
        $kv->set('find', $find);

        $contentStr = "选择表情旁边的'+',发送位置,即可查找你要找的地方";
        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgtype, $contentStr);
        echo $resultStr;
        exit();

      }

Copy after login
 elseif($postObj->MsgType == 'location'){
          /**
           * 如果是收到了地理位置消息,则返回附近的饭店
           */

          //--------第一步:转换经纬度-------
          //参考链接:http://developer.baidu.com/map/index.php&#63;title=webapi/guide/changeposition
          $Location_X = $postObj->Location_X;
          $Location_Y = $postObj->Location_Y;
          
          $url = "http://api.map.baidu.com/geoconv/v1/&#63;coords=$Location_X,$Location_Y&from=3&to=5&ak=这里填写你的apikey";
          
          $res = file_get_contents($url);
          $res = json_decode($res, true);

          //用户发送腾讯的soso地图位置信息经过转换之后,得到百度地图的经纬度
          $x = $res['result'][0]['x'];
          $y = $res['result'][0]['y'];

          //---------第二步:根据经纬度和关键词获得附近的信息----------
          $kv = new SaeKV();
          // 初始化KVClient对象
          $kv->init();
          
          $url = "http://api.map.baidu.com/place/v2/search&#63;ak=这里填写你的apikey&output=json&query=" . urlencode($kv->get('find')) . "&page_size=10&page_num=0&scope=2&location=$x,$y&radius=2000";
          $res = file_get_contents($url);
          $res = json_decode($res, true);
          
          //提取信息
          foreach($res['results'] as $k=>$v){
            $arr[$k]['name'] = $v['name'];
            $arr[$k]['address'] = $v['address'];
            $arr[$k]['img_url'] = 'http://misakaqnxt-public.stor.sinaapp.com/click.png';
            $arr[$k]['detail_url'] = isset($v['detail_info']['detail_url'])&#63;$v['detail_info']['detail_url']:'';
          }

          //--------第三步:拼接XML字符串--------
          $head = "<xml>
          <ToUserName><![CDATA[%s]]></ToUserName>
          <FromUserName><![CDATA[%s]]></FromUserName>
          <CreateTime>%s</CreateTime>
          <MsgType><![CDATA[news]]></MsgType>
          <ArticleCount>10</ArticleCount>
          <Articles>";

          $items = "";
          foreach($arr as $v){
            $items .= "<item>
            <Title><![CDATA[" . $v['name'] .":". $v['address'] . "]]></Title>
            <Description><![CDATA[" . $v['address'] . "]]></Description>
            <PicUrl><![CDATA[" . $v['img_url'] . "]]></PicUrl>
            <Url><![CDATA[" . $v['detail_url'] . "]]></Url>
            </item>";
          }

          $foot = "</Articles></xml>";

          $res = $head . $items . $foot;
          
          $resultStr = sprintf($res, $fromUsername, $toUsername, $time);
          echo $resultStr;
          exit();


} 

Copy after login

If you don’t understand how to use the code, you can refer to my previous article: Simple text reply Query WeChat selected articles

After users follow the official account, reply to search for a hotel, and then reply with the geographical location, they can get nearby hotel information.

The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope that everyone will support Script House.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template