Home > WeChat Applet > WeChat Development > WeChat public platform message interface development example of geographical location query for nearby businesses

WeChat public platform message interface development example of geographical location query for nearby businesses

高洛峰
Release: 2017-03-31 14:50:28
Original
3434 people have browsed it

1. Obtain user address location message

The message and format when the user sends the location is as follows

WeChat public platform message interface development example of geographical location query for nearby businesses

Backend format:

<xml>
<ToUserName><![CDATA[gh_680bdefc8c5d]]></ToUserName>
<FromUserName><![CDATA[oIDrpjqASyTPnxRmpS9O_ruZGsfk]]></FLACFromUserName>
<CreateTime>1359036619</CreateTime>
<MsgType><![CDATA[location]]></MsgType>
<Location_X>22.539968</Location_X>
<Location_Y>113.954980</Location_Y>
<Scale>16</Scale>
<Label><![CDATA[中国广东省深圳市南山区华侨城深南大道9789号 邮政编码: 518057]]></Label>
<MsgId>5837017832671832047</MsgId>
</xml>
Copy after login

XML format explanation


ToUserName 消息接收方微信号,一般为公众平台账号微信号
 FromUserName 消息发送方微信号
 CreateTime 消息创建时间
 MsgType 消息类型,地理位置为location
 Location_X 地理位置纬度
 Location_Y 地理位置经度
 Scale 地图缩放大小
 Label 地理位置信息
 MsgId 消息ID号
Copy after login

2. Obtain surrounding area information

Baidu Map Place API is a simple HTTP interface, used In order to return and query certain types of POI data in a certain area, and provide detailed query services for a single POI, users can use C#, C++, Java and other development languages ​​to send HTTP requests and receive json, xml data.

Place API provides regional search POI services, POI details services, group purchase information retrieval services, and merchant group purchase details inquiries. The regional search POI service provides three regional search methods: within-city search, rectangular search, and circular area search.

We use circular area retrieval to implement the nearby search function.

place area retrieval POI service interface is as follows:

http://api.map.baidu.com/place/v2/search

##None2000Peripheral search radius, unit is meterq(query)isNoneZhongguancun, ATM, Baidu Building Search keywords, surrounding search and rectangular area Internal search supports union search of multiple keywords. Different keywords are separated by $ symbol, and up to 10 keyword searches are supported. For example: "Bank$Hotel". tagNoNoneJapanese BBQ/Teppanyaki, Chaowai StreetTag items, combined with q to searchoutputNoxmljson or xmlThe output format is json or xmlscopeis11, 2 Search result detail level. If the value is 1 or empty, basic information is returned; if the value is 2, detailed POI information is returnedfilterNoNone |sort_name:price industry_type: Industry type

Parameters

Whether it is required

Default value

Format example

Meaning

location

is

None

##38.76623, 116.43213

lat,lng

Peripheral search center point, multiple points are not supported

radius(r)

No

##filter=industry_type:cater
|sort_rule:0

|price_section:100,200
|groupon:0
|discount:0


Retrieve filter conditions. When the scope value is 2, you can set the filter for sorting.
sort_name: Sorting field

sort_rule: Sorting rule, the values ​​are as follows: 0: from high to low, 1: from low to high;
price_section: price range;
groupon: whether there is group buying, 1 means there is group buying, 0 means no group buying;
discount: whether there is a discount, 1 means there is a discount, 0 means there is no discount;

page_size

10

10

范围记录数量,默认为10条记录,最大返回20条。多关键字检索时,返回的记录数为关键字个数*page_size。

page_num

0

0、1、2

分页页码,默认为0,0代表第一页,1代表第二页,以此类推。

ak

E4805d16520de693a3fe707cdc962045

用户的访问密钥,必填项。v2之前该属性为key。

sn

 

用户的权限签名。

timestamp

 

设置sn后该值必填。

调用举例如下:


http://api.map.baidu.com/place/v2/search?ak=MgBALVVeCd8THVBi6gPdvsvG&output=json&query=%E9%93%B6%E8%A1%8C&page_size=5&page_num=0&scope=2&location=39.915,116.404&radius=2000&filter=sort_name:distance
Copy after login

三、程序实现

百度地图类定义如下

class baiduMapClient
{    
    private $api_server_url;
    private $auth_params;

    public function __construct()
    {
        $this->api_server_url = "http://api.map.baidu.com/";
        $this->auth_params = array();
           $this->auth_params[&#39;key&#39;] = "401f9a693dd267dd9a4661ec0895fb20";
        $this->auth_params[&#39;output&#39;] = "json";
    }

    public function Geocoding_coordinate_address($location) 
    {   
        return $this->call("geocoder", array("location" => $location));
    }
    
    //http://api.map.baidu.com/place/search?&query=眼镜&location=39.915,116.404&radius=3000&output=json&key=37492c0ee6f924cb5e934fa08c6b1676
    public function Place_search($query, $location, $radius) 
    {
        return $this->call("place/search", array("query" => $query, "location" => $location, "radius" => $radius));
    }
    
    protected function call($method, $params = array())
    {
        $headers = array(
            "User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:14.0) Gecko/20100101 Firefox/14.0.1",
            "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
            "Accept-Language: en-us,en;q=0.5",
            //"Accept-Encoding: gzip, deflate",
            "Referer: http://developer.baidu.com/"
        );
        $params = array_merge($this->auth_params, $params);
        $url = $this->api_server_url . "$method?".http_build_query($params);
        if (DEBUG_MODE){echo "REQUEST: $url" . "\n";}
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
         $data = curl_exec($ch);
        curl_close($ch);    
        $result = null;
        if (!empty($data)){
            if (DEBUG_MODE){
                echo "RETURN: " . $data . "\n";
            }
            $result = json_decode($data);
        }
        else{
            echo "cURL Error:". curl_error($ch);
        }
        return $result;
    }
}
Copy after login

获取附近的调用代码如下:

function catchEntitiesFromLocation($entity, $x, $y, $radius)
{   
    $mapObj = new baiduMapClient();
    $search = $mapObj->Place_search($entity, $x.",".$y, $radius);
    $results = $search->results;
    for ($i = 0; $i < count($results); $i++) {
        $distance = getDistance($x, $y, $results[$i]->location->lat, $results[$i]->location->lng);
        $shopSortArrays[$distance] = array(
            "Title"=>"【".$results[$i]->name."】<".$distance."M>".$results[$i]->address.(isset($results[$i]->telephone)?" ".$results[$i]->telephone:""),
            "Description"=>"", 
            "PicUrl"=>"", 
            "Url"=>"");
    }
    ksort($shopSortArrays);//排序
    $shopArray = array(); 
    foreach ($shopSortArrays as $key => $value) {  
        $shopArray[] =  array(
                        "title" => $value["Title"],
                        "description" => $value["Description"],
                        "pic" => $value["PicUrl"],
                        "url" => $value["Url"],
                    );
        if (count($shopArray) > 6){break;}
    }
    return $shopArray;
}
Copy after login

计算两坐标之间距离如下

function getDistance($lat_a, $lng_a, $lat_b, $lng_b) {
    //R是地球半径(米)
    $R = 6366000;
    $pk = doubleval(180 / 3.14169);
    
    $a1 = doubleval($lat_a / $pk);
    $a2 = doubleval($lng_a / $pk);
    $b1 = doubleval($lat_b / $pk);
    $b2 = doubleval($lng_b / $pk);

    $t1 = doubleval(cos($a1) * cos($a2) * cos($b1) * cos($b2));
    $t2 = doubleval(cos($a1) * sin($a2) * cos($b1) * sin($b2));
    $t3 = doubleval(sin($a1) * sin($b1));
    $tt = doubleval(acos($t1 + $t2 + $t3));

    return round($R * $tt);
}
Copy after login

对于用户的坐标记录,我们使用数据库的方式来存储,

如果用户发送查询命令,则直接查询,

function searchUserLocation($userWxid)
{
    Global $mysql_host;
    Global $mysql_host_s;
    Global $mysql_port;
    Global $mysql_user;
    Global $mysql_password;
    Global $mysql_database;
    
    //查询使用从库,支持SAE
    $mysql_table = "location";
    $mysql_state = "SELECT * FROM ".$mysql_table." WHERE userWxid = \"".$userWxid."\"";
    $con = mysql_connect($mysql_host.&#39;:&#39;.$mysql_port, $mysql_user, $mysql_password);
    if (!$con){
        die(&#39;Could not connect: &#39; . mysql_error());
    }
    mysql_query("SET NAMES &#39;UTF8&#39;");
    mysql_select_db($mysql_database, $con);
    $result = mysql_query($mysql_state);
    $location = array(); 
    while($row = mysql_fetch_array($result))
    {
        $location["x"] = $row["locationX"]; 
        $location["y"] = $row["locationY"]; 
    }
    mysql_close($con);
    if (isset($location["x"]) && $location["x"] != 0.0){
        return $location;
    }else{
        return "系统中没有你的地理位置信息,请先发送位置给我!您不用担心你的行踪被泄漏,因为你可以滑动地图,把别处的地址发送过来。";
    }
    
}
Copy after login

如果用户发了位置,则进行更新

function updateOrInsert($weixinid, $locationX, $locationY)
{    
    if (isset($_SERVER[&#39;HTTP_APPNAME&#39;])){
        $mysql_host = SAE_MYSQL_HOST_M;
        $mysql_host_s = SAE_MYSQL_HOST_S;  //sae的从库
        $mysql_port = SAE_MYSQL_PORT;
        $mysql_user = SAE_MYSQL_USER;
        $mysql_password = SAE_MYSQL_PASS;
        $mysql_database = SAE_MYSQL_DB;
    }else{
        $mysql_host = "127.0.0.1";
        $mysql_host_s = "127.0.0.1";
        $mysql_port = "3306";
        $mysql_user = "root";
        $mysql_password = "root";
        $mysql_database = "sae";
    }
    
    $mysql_table = "location";
    //INSERT INTO location VALUES("23s2s", 1122.2, 366.2) ON DUPLICATE KEY UPDATE locationX = 1122.2, locationY = 366.2;
    
    $mysql_state = "INSERT INTO ".$mysql_table." VALUES(\"".$weixinid."\", ".$locationX.", ".$locationY.") ON DUPLICATE KEY UPDATE locationX = ".$locationX.", locationY = ".$locationY.";";
    var_dump($mysql_state);
    //
    
    $con = mysql_connect($mysql_host.&#39;:&#39;.$mysql_port, $mysql_user, $mysql_password);
    if (!$con){
        die(&#39;Could not connect: &#39; . mysql_error());
    }
    mysql_query("SET NAMES &#39;UTF8&#39;");
    mysql_select_db($mysql_database, $con);
    $result = mysql_query($mysql_state);
    if ($result == true){
        //return "你提交的位置为纬度:".$locationX.",经度:".$locationY."。\n现在可以发送“附近”加关键字的命令查询附近的目标,如“附近酒店”,“附近医院”。";
        return "已经成功获取你的位置。您不用担心你的行踪被泄漏,因为你可以把千里之外的地址提交过来。\n现在可以发送“附近”加关键字的命令查询附近的目标,如“附近酒店”,“附近医院”。";
    }else{
        return "提交失败,请重试。如果一直出现这样的错误,请给我们留言。";
    }
}
Copy after login

对于用户发送的内容,先提取坐标,然后进行组合查询

WeChat public platform message interface development example of geographical location query for nearby businesses

实现效果如下:

 WeChat public platform message interface development example of geographical location query for nearby businessesWeChat public platform message interface development example of geographical location query for nearby businessesWeChat public platform message interface development example of geographical location query for nearby businesses

 

The above is the detailed content of WeChat public platform message interface development example of geographical location query for nearby businesses. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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