WeChat public platform Message Interface development geographic location query nearby merchant instances

Source: Internet
Author: User
Tags map class
This article describes in detail the development of the message interface on the public platform and the query of information about nearby merchant instances. For more information, see 1. get the user address location message

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

Background format:

 
  gh_680bdefc8c5d
  
  oIDrpjqASyTPnxRmpS9O_ruZGsfk
   
    
1359036619
   
   location
   
   
    
22.539968
   
   
    
113.954980
   
   
    
16
   
   中国广东省深圳市南山区华侨城深南大道9789号 邮政编码: 518057
   
    
5837017832671832047
   
  
 

XML Format Description


ToUserName: message recipient number. generally, it is the public platform account number FromUserName. the message sender number is CreateTime. the Message creation time is MsgType, geographic location: location Location_X geographic location latitude Location_Y geographic location longitude Scale map scaling size Label Geographic location information MsgId message ID
2. obtain information about the surrounding area

Baidu Map Place API is a simple HTTP interface used to return and query certain types of POI data in a region, and provides a single POI details query service, you can use C #, C ++, Java, and other development languages to send HTTP requests and receive json and xml data.

The Place API provides regional search POI service, POI details Service and group buying information retrieval service, and merchant group buying details query. The regional search POI service provides three regional search methods: intra-city search, rectangular search, and circular area search.

We use circular area search to implement nearby search.

The service interface for searching POI in the place region is as follows:

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

Parameters

Required?

Default value

Format example

Description

Location

Yes

None

38.76623, 116.43213
Lat <纬度> , Lng <经度>

Peripheral retrieval center. Multiple points are not supported.

Radius (r)

No

None

2000

Peripheral search radius, in meters

Q (query)

Yes

None

Zhongguancun, ATM, Baidu Tower

Search keywords. The search in the surrounding area and the search in the rectangle area support multiple keywords in parallel. different keywords are separated by the $ symbol, and a maximum of 10 keywords can be searched. For example, "Bank $ Hotel ".

Tag

No

None

Japanese barbecue/teppanyaki, Chaowai Street

Tag item, which can be searched in combination with q

Output

No

Xml

Json or xml

The output format is json or xml.

Scope

Yes

1

1, 2

The details of the search results. If the value is 1 or null, basic information is returned. if the value is 2, POI details are returned.

Filter

No

None

Filter = industry_type: cater
| Sort_name: price
| Sort_rule: 0
| Price_section: 100,200
| Groupon: 0
| Discount: 0

Search for filtering conditions. when the scope value is 2, you can set filter to sort.
Industry_type: Industry Type
Sort_name: sorting field
Sort_rule: sorting rule. values: 0: from high to low; 1: from low to high;
Price_section: price range;
Groupon: whether there are group purchases. 1 is group purchases, and 0 is group purchases;
Discount: indicates whether a discount is made. 1 indicates a discount, and 0 indicates no discount;

Page_size

No

10

10

Number of records in the range. the default value is 10, and a maximum of 20 records are returned. When multiple keywords are retrieved, the number of records returned is the number of keywords * page_size.

Page_num

No

0

0, 1, 2

Page number. the default value is 0, 0, which indicates the first page, 1 indicates the second page, and so on.

Ak

Yes

None

E4805d16520de693a3fe707gj962045

The user's access key, required. This attribute is key before v2.

Sn

No

None

 

The user's permission signature.

Timestamp

No

None

 

This value is required after sn is set.

Call example:


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

3. program implementation

Baidu Map class is defined as follows

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 ['key'] =" 401f9a693dd267dd9a4661ec0895fb20 "; $ this-> auth_params ['output'] = "json";} public function Geocoding_coordinate_address ($ location) {return $ this-> call ("geocoder ", array ("location" => $ location ));}// http://api.map.baidu.com/ Place/search? & Query = glasses & location = 39.915, 116.404 & radius = 3000 & output = json & key = 37109c0ee6f924cb5e934fa08c6b1676 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 ;}}

Obtain the nearby call code as follows:

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); // Sort $ 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 ;}

The distance between two coordinates is calculated as follows:

Function getDistance ($ lat_a, $ lng_a, $ lat_ B, $ lng_ B) {// R is the Earth's radius (meters) $ 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 );}

We use databases to store user coordinate records,

If you send a query command, you can directly query,

Function searchUserLocation ($ userWxid) {Global $ mysql_host; Global $ mysql_host_s; Global $ mysql_port; Global $ mysql_user; Global $ mysql_password; Global $ mysql_database; // query slave database, support SAE $ mysql_table = "location"; $ mysql_state = "SELECT * FROM ". $ mysql_table. "WHERE userWxid = \"". $ userWxid. "\" "; $ con = mysql_connect ($ mysql_host. ':'. $ mysql_port, $ mysql_user, $ mysql_password); if (! $ Con) {die ('could not connect :'. mysql_error ();} mysql_query ("set names 'utf8'"); 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 "the system does not contain your geographic location information. please send the location to me first! You don't have to worry about your whereabouts being leaked because you can slide the map and send the addresses elsewhere. ";}}

If the user sends the location, update it.

Function updateOrInsert ($ weixinid, $ locationX, $ locationY) {if (isset ($ _ SERVER ['http _ appname']) {$ mysql_host = SAE_MYSQL_HOST_M; $ mysql_host_s = bytes; // sae slave database $ mysql_port = SAE_MYSQL_PORT; $ mysql_user = SAE_MYSQL_USER; $ mysql_password = SAE_MYSQL_PASS; $ mysql_database = slave;} else {$ mysql_host = "127.0.0.1 "; $ mysql_host_s = "127.0.0.1"; $ mysql_port = "3306"; $ mysql_user = "ro Ot "; $ 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 ". $ mysql_table. "VALUES (\"". $ weixinid. "\",". $ locationX. ",". $ locationY. ") on duplicate key update locationX = ". $ locationX. ", locationY = ". $ locationY. ";"; var_dump ($ mys Ql_state); // $ con = mysql_connect ($ mysql_host. ':'. $ mysql_port, $ mysql_user, $ mysql_password); if (! $ Con) {die ('could not connect :'. mysql_error ();} mysql_query ("set names 'utf8'"); mysql_select_db ($ mysql_database, $ con); $ result = mysql_query ($ mysql_state ); if ($ result = true) {// return "the submitted position is latitude :". $ locationX. ", Longitude :". $ locationY. ". \ N can now send "nearby" and keyword commands to query nearby targets, such as "nearby hotels" and "nearby hospitals ". "; Return" your location has been obtained successfully. You don't have to worry about your whereabouts being leaked, because you can submit the address thousands of miles away. \ N can now send "nearby" and keyword commands to query nearby targets, such as "nearby hotels" and "nearby hospitals ". ";} Else {return" failed to submit. please try again. If this error persists, please leave a message. ";}}

For the content sent by the user, extract the coordinates and perform combined query.

The preceding figure shows the details of nearby merchant instances in the development of the message interface on the public platform. For more information, see other related articles on php Chinese network!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.