Collection of code examples of location information API calls: urban area query, POI search, etc

The following example code applies to www.apishop.net For the API under the website, you need to apply for the corresponding API service before using the interface call code examples mentioned in this article.

  1. Query of urban areas in China : 2017 latest City address of China Province
  2. Latitude and longitude address conversion : latitude and longitude address conversion
  3. POI search : query POI information in a region through keywords, and support city level, district and county level queries: for example, query "bank" in Guangzhou, and the interface will output the list of geographic information of all banks.
  4. Bus and subway route planning : public transport, driving, cycling, walking query, return the retrieval data in json format.

API Shop (apishop.net) provides up to 50 commonly used third-party APIs. You can download the code sample collection from github: https://github.com/apishop/All-APIs

The above interfaces include code examples of PHP, Python, C เท and Java. Take the route query API as an example:

(1) Code example of route query API service request based on PHP

<?php
$method = "POST";
$url = "https://api.apishop.net/common/direction/queryRoutes";
$headers = NULL;
$params = array(
    "origin" => "", //The starting point name or longitude and latitude, or the name and longitude and latitude can be provided at the same time. At this time, the longitude and latitude priority is high, which will be used as the navigation basis, and the name is only responsible for display. In case of pedestrian route planning, the straight-line distance between the start and end points shall not exceed 200 km. Such as "Guangzhou tower", "Guangzhou tower ๐ž“œ 23.114155113.318977"
    "destination" => "", //The end point name or longitude and latitude, or the name and longitude and latitude can be provided at the same time. At this time, the longitude and latitude have a high priority and will be used as the navigation basis. The name is only responsible for display. In case of pedestrian route planning, the straight-line distance between the start and end points shall not exceed 200 km. Such as "Guangzhou tower", "Guangzhou tower ๐ž“œ 23.114155113.318977"
    "mode" => "", //Navigation mode, including driving, walking, transit and riding, default to transit
    "region" => "", //This parameter is required for the city, bus and pedestrian navigation.
    "origin_region" => "", //The city where the starting point is located, required for driving navigation.
    "destination_region" => "", //Destination city, required for driving navigation.
    "coord_type" => "", //Coordinate type, bd09ll by default. The allowed values are: bd09ll (Baidu latitude and longitude coordinate), bd09mc (Baidu motorcycle coordinate), gcj02 (National Survey Bureau encrypted coordinate), wgs84 (coordinate obtained by gps equipment).
    "ret_coordtype" => "", //Optional, the default is Baidu latitude and longitude coordinate: bd09ll optional value: bd09ll: Baidu latitude and longitude coordinate gcj02: CSB coordinate
    "waypoints" => "", //A set of waypoints, including one or more address names or longitudes separated by the vertical character "|". Support driving and walking programs, and support up to 5 passing points.
    "tactics" => "", //Navigation policy, default is 12. Optional values: 10: no high-speed; 11: regular route, a route most people often take, which is not affected by road conditions and can be used for vehicle evaluation; 12: short distance, a relatively short route, but not necessarily a high-quality route; 13: avoid congestion   
);

$result = apishop_curl($method, $url, $headers, $params);
If ($result) {
    $body = json_decode($result["body"], TRUE);
    $status_code = $body["statusCode"];
    If ($status_code == "000000") {
        //The status code is 000000, indicating that the request is successful
        echo "Request successful:" . $result["body"];
    } else {
        //The status code is not 000000, indicating that the request failed
        echo "Request failed:" . $result["body"];
    }
} else {
    //The content returned is abnormal. Sending the request failed. The following can be modified according to the business logic
    echo "Send request failed";
}

/**
 * Forward request to destination host
 * @param $method string Request method
 * @param $URL string Request address
 * @param null $headers Request header
 * @param null $param Request parameters
 * @return array|bool
 */
function apishop_curl(&$method, &$URL, &$headers = NULL, &$param = NULL)
{
    // Initialize request
    $require = curl_init($URL);
    // Determine whether HTTPS
    $isHttps = substr($URL, 0, 8) == "https://" ? TRUE : FALSE;
    // Set request method
    switch ($method) {
        case "GET":
            curl_setopt($require, CURLOPT_CUSTOMREQUEST, "GET");
            break;
        case "POST":
            curl_setopt($require, CURLOPT_CUSTOMREQUEST, "POST");
            break;
        default:
            return FALSE;
    }
    if ($param) {
        curl_setopt($require, CURLOPT_POSTFIELDS, $param);
    }
    if ($isHttps) {
        // Skip certificate check
        curl_setopt($require, CURLOPT_SSL_VERIFYPEER, FALSE);
        // Check whether the domain name is set in the certificate
        curl_setopt($require, CURLOPT_SSL_VERIFYHOST, 2);
    }
    if ($headers) {
        // Set request header
        curl_setopt($require, CURLOPT_HTTPHEADER, $headers);
    }
    // Return result is not output directly
    curl_setopt($require, CURLOPT_RETURNTRANSFER, TRUE);
    // redirect
    curl_setopt($require, CURLOPT_FOLLOWLOCATION, TRUE);
    // Include the return header in the output
    curl_setopt($require, CURLOPT_HEADER, TRUE);
    // Send request
    $response = curl_exec($require);
    // Get head length
    $headerSize = curl_getinfo($require, CURLINFO_HEADER_SIZE);
    // Close request
    curl_close($require);
    if ($response) {
        // Return header string
        $header = substr($response, 0, $headerSize);
        // Return body
        $body = substr($response, $headerSize);
        // Filter hidden illegal characters
        $bodyTemp = json_encode(array(
            0 => $body
        ));
        $bodyTemp = str_replace("\ufeff", "", $bodyTemp);
        $bodyTemp = json_decode($bodyTemp, TRUE);
        $body = trim($bodyTemp[0]);
        // Turn the returned result header into an array
        $respondHeaders = array();
        $header_rows = array_filter(explode(PHP_EOL, $header), "trim");
        foreach ($header_rows as $row) {
            $keylen = strpos($row, ":");
            if ($keylen) {
                $respondHeaders[] = array(
                    "key" => substr($row, 0, $keylen),
                    "value" => trim(substr($row, $keylen + 1))
                );
            }
        }
        return array(
            "headers" => $respondHeaders,
            "body" => $body
        );
    } else {
        return FALSE;
    }
}

(2) Code example of route query API service request based on Python

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Test environment: python2.7
# Install requests dependency = > PIP install requests/ easy install requests

# Import requests dependency
import requests
import json
import sys

reload(sys)
sys.setdefaultencoding('utf-8')

def apishop_send_request(method, url, params=None, headers=None):
    '''
    //Forward request to destination host
    @param method str Request method
    @param url str Request address
    @param params dict Request parameters
    @param headers dict Request header
    '''
    method = str.upper(method)
    if method == 'POST':
        return requests.post(url=url, data=params, headers=headers)
    elif method == 'GET':
        return requests.get(url=url, params=params, headers=headers)
    else:
        return None

method = "POST"
url = "https://api.apishop.net/common/direction/queryRoutes"
headers = None
params = {          
    "origin":"", #The starting point name or longitude and latitude, or the name and longitude and latitude can be provided at the same time. At this time, the longitude and latitude priority is high, which will be used as the navigation basis, and the name is only responsible for display. In case of pedestrian route planning, the straight-line distance between the start and end points shall not exceed 200 km. Such as "Guangzhou tower", "Guangzhou tower ๐ž“œ 23.114155113.318977"
    "destination":"", #The end point name or longitude and latitude, or the name and longitude and latitude can be provided at the same time. At this time, the longitude and latitude have a high priority and will be used as the navigation basis. The name is only responsible for display. In case of pedestrian route planning, the straight-line distance between the start and end points shall not exceed 200 km. Such as "Guangzhou tower", "Guangzhou tower ๐ž“œ 23.114155113.318977"
    "mode":"", #Navigation mode, including driving, walking, transit and riding, default to transit
    "region":"", #This parameter is required for the city, bus and pedestrian navigation.
    "origin_region":"", #The city where the starting point is located, required for driving navigation.
    "destination_region":"", #Destination city, required for driving navigation.
    "coord_type":"", #Coordinate type, bd09ll by default. The allowed values are: bd09ll (Baidu latitude and longitude coordinate), bd09mc (Baidu motorcycle coordinate), gcj02 (National Survey Bureau encrypted coordinate), wgs84 (coordinate obtained by gps equipment).
    "ret_coordtype":"", #Optional, the default is Baidu latitude and longitude coordinate: bd09ll optional value: bd09ll: Baidu latitude and longitude coordinate gcj02: CSB coordinate
    "waypoints":"", #A set of waypoints, including one or more address names or longitudes separated by the vertical character "|". Support driving and walking programs, and support up to 5 passing points.
    "tactics":"", #Navigation policy, default is 12. Optional values: 10: no high-speed; 11: regular route, a route most people often take, which is not affected by road conditions and can be used for vehicle evaluation; 12: short distance, a relatively short route, but not necessarily a high-quality route; 13: avoid congestion
}
result = apishop_send_request(method=method, url=url, params=params, headers=headers)
if result:
    body = result.text
    response = json.loads(body)
    status_code = response["statusCode"]
    if (status_code == '000000'):
        # The status code is 000000, indicating that the request is successful
        print('Request successful:%s' % (body,))
    else:
        # The status code is not 000000, indicating that the request failed
        print('request was aborted: %s' % (body,))
else:
    # Return content exception, send request failed
    print('Send request failed')

(3) Code example of route query API service request based on C เท

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Web.Script.Serialization;

namespace apishop_sdk
{
class Program
{
    /**
     * Forward request to destination host
     * @param method string Request method
     * @param url string Request address
     * @param params Dictionary<string,string> Request parameters
     * @param headers Dictionary<string,string> Request header
     * @return string
    **/
    static string apishop_send_request(string method, string url, Dictionary<string, string> param, Dictionary<string, string> headers)
    {
        string result = string.Empty;
        try
            {
                string paramData = "";
                if (param != null && param.Count > 0)
                {
                    StringBuilder sbuilder = new StringBuilder();
                    foreach (var item in param)
                    {
                        if (sbuilder.Length > 0)
                        {
                            sbuilder.Append("&");
                        }
                        sbuilder.Append(item.Key + "=" + item.Value);
                    }
                    paramData = sbuilder.ToString();
                }
                method = method.ToUpper();
                if (method == "GET")
                {
                    url = string.Format("{0}?{1}", url, paramData);
                }
                HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url);
                if (method == "GET")
                {
                    wbRequest.Method = "GET";
                }
                else if (method == "POST")
                {
                    wbRequest.Method = "POST";
                    wbRequest.ContentType = "application/x-www-form-urlencoded";
                    wbRequest.ContentLength = Encoding.UTF8.GetByteCount(paramData);
                    using (Stream requestStream = wbRequest.GetRequestStream())
                    {
                        using (StreamWriter swrite = new StreamWriter(requestStream))
                        {
                            swrite.Write(paramData);
                        }
                    }
                }

                HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse();
                using (Stream responseStream = wbResponse.GetResponseStream())
                {
                    using (StreamReader sread = new StreamReader(responseStream))
                    {
                        result = sread.ReadToEnd();
                    }
                }
            }
            catch
            {
                return "";
            }
            return result;
        }
        class Response
        {
            public string statusCode;
        }
        static void Main(string[] args)
        {
            string method = "POST";
            string url = "https://api.apishop.net/common/direction/queryRoutes";
            Dictionary<string, string> param = new Dictionary<string, string>();            
            param.Add("origin", ""); //The starting point name or longitude and latitude, or the name and longitude and latitude can be provided at the same time. At this time, the longitude and latitude priority is high, which will be used as the navigation basis, and the name is only responsible for display. In case of pedestrian route planning, the straight-line distance between the start and end points shall not exceed 200 km. Such as "Guangzhou tower", "Guangzhou tower ๐ž“œ 23.114155113.318977"
    param.Add("destination", ""); //The end point name or longitude and latitude, or the name and longitude and latitude can be provided at the same time. At this time, the longitude and latitude have a high priority and will be used as the navigation basis. The name is only responsible for display. In case of pedestrian route planning, the straight-line distance between the start and end points shall not exceed 200 km. Such as "Guangzhou tower", "Guangzhou tower ๐ž“œ 23.114155113.318977"
    param.Add("mode", ""); //Navigation mode, including driving, walking, transit and riding, default to transit
    param.Add("region", ""); //This parameter is required for the city, bus and pedestrian navigation.
    param.Add("origin_region", ""); //The city where the starting point is located, required for driving navigation.
    param.Add("destination_region", ""); //Destination city, required for driving navigation.
    param.Add("coord_type", ""); //Coordinate type, bd09ll by default. The allowed values are: bd09ll (Baidu latitude and longitude coordinate), bd09mc (Baidu motorcycle coordinate), gcj02 (National Survey Bureau encrypted coordinate), wgs84 (coordinate obtained by gps equipment).
    param.Add("ret_coordtype", ""); //Optional, the default is Baidu latitude and longitude coordinate: bd09ll optional value: bd09ll: Baidu latitude and longitude coordinate gcj02: CSB coordinate
    param.Add("waypoints", ""); //A set of waypoints, including one or more address names or longitudes separated by the vertical character "|". Support driving and walking programs, and support up to 5 passing points.
    param.Add("tactics", ""); //Navigation policy, default is 12. Optional values: 10: no high-speed; 11: regular route, a route most people often take, which is not affected by road conditions and can be used for vehicle evaluation; 12: short distance, a relatively short route, but not necessarily a high-quality route; 13: avoid congestion

            Dictionary<string, string> headers = null;
            string result = apishop_send_request(method, url, param, headers);
            if (result == "")
            {
                //Return content exception, send request failed
                Console.WriteLine("Send request failed");
                return;
            }

            Response res = new JavaScriptSerializer().Deserialize<Response>(result);
            if (res.statusCode == "000000")
            {
                //The status code is 000000, indicating that the request is successful
                Console.WriteLine(string.Format("Request successful: {0}", result));
            }
            else
            {
                //The status code is not 000000, indicating that the request failed
                Console.WriteLine(string.Format("request was aborted: {0}", result));
            }
            Console.ReadLine();
        }
    }
}

(4) Code example of route query API service request based on Java

package net.apishop.www.controller;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.fastjson.JSONObject;

/**
* httpUrlConnection Access remote interface tools
*/
public class Api
{
    /**
    * Method body description: initiates a request to the remote interface and returns the byte stream type result
    * param url Interface address
    * param requestMethod Request mode
    * param params Key points of passing parameters: the parameter value needs to be transcoded with Base64
    * return InputStream Return result
    */
    public static InputStream httpRequestToStream(String url, String requestMethod, Map<String, String> params){
        InputStream is = null;
        try{
            String parameters = "";
            boolean hasParams = false;
            // Splice parameter sets into specific formats, such as name = Zhangsan & age = 24
            for (String key : params.keySet()){
                String value = URLEncoder.encode(params.get(key), "UTF-8");
                parameters += key + "=" + value + "&";
                hasParams = true;
            }
            if (hasParams){
                parameters = parameters.substring(0, parameters.length() - 1);
            }
            // Whether the request method is get
            boolean isGet = "get".equalsIgnoreCase(requestMethod);
            // Whether the request mode is post
            boolean isPost = "post".equalsIgnoreCase(requestMethod);
            if (isGet){
                url += "?" + parameters;
            }
            URL u = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) u.openConnection();
            // Parameter type requested (when using restlet framework, content type must be set to "" empty in order to be compatible with framework)
            conn.setRequestProperty("Content-Type", "application/octet-stream");
            //conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            // Set connection timeout
            conn.setConnectTimeout(50000);
            // Set the time-out for reading returned content
            conn.setReadTimeout(50000);
            // Set to output to the HttpURLConnection object, because the post mode places the request parameter in the http body, so it needs to be set to true, and the default is false
            if (isPost){
                conn.setDoOutput(true);
            }
            // Set to read from HttpURLConnection object, default to true
            conn.setDoInput(true);
            // Set whether to use cache or not. post mode cannot use cache
            if (isPost){
                conn.setUseCaches(false);
            }
            // Set request mode, default to GET
            conn.setRequestMethod(requestMethod);
            // post mode needs to output the passed parameters to the conn object
            if (isPost){
                DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
                dos.writeBytes(parameters);
                dos.flush();
                dos.close();
            }
            // Read the message of the response from the HttpURLConnection object
            // The request is only formally initiated when the statement is executed
            is = conn.getInputStream();
        }catch(UnsupportedEncodingException e){
            e.printStackTrace();
        }catch(MalformedURLException e){
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }
        return is;
    }

    public static void main(String args[]){
        String url = "https://api.apishop.net/common/direction/queryRoutes";
        String requestMethod = "POST";
        Map<String, String> params = new HashMap<String, String>();         
        params.put("origin", ""); //The starting point name or longitude and latitude, or the name and longitude and latitude can be provided at the same time. At this time, the longitude and latitude priority is high, which will be used as the navigation basis, and the name is only responsible for display. In case of pedestrian route planning, the straight-line distance between the start and end points shall not exceed 200 km. Such as "Guangzhou tower", "Guangzhou tower ๐ž“œ 23.114155113.318977"
    params.put("destination", ""); //The end point name or longitude and latitude, or the name and longitude and latitude can be provided at the same time. At this time, the longitude and latitude have a high priority and will be used as the navigation basis. The name is only responsible for display. In case of pedestrian route planning, the straight-line distance between the start and end points shall not exceed 200 km. Such as "Guangzhou tower", "Guangzhou tower ๐ž“œ 23.114155113.318977"
    params.put("mode", ""); //Navigation mode, including driving, walking, transit and riding, default to transit
    params.put("region", ""); //This parameter is required for the city, bus and pedestrian navigation.
    params.put("origin_region", ""); //The city where the starting point is located, required for driving navigation.
    params.put("destination_region", ""); //Destination city, required for driving navigation.
    params.put("coord_type", ""); //Coordinate type, bd09ll by default. The allowed values are: bd09ll (Baidu latitude and longitude coordinate), bd09mc (Baidu motorcycle coordinate), gcj02 (National Survey Bureau encrypted coordinate), wgs84 (coordinate obtained by gps equipment).
    params.put("ret_coordtype", ""); //Optional, the default is Baidu latitude and longitude coordinate: bd09ll optional value: bd09ll: Baidu latitude and longitude coordinate gcj02: CSB coordinate
    params.put("waypoints", ""); //A set of waypoints, including one or more address names or longitudes separated by the vertical character "|". Support driving and walking programs, and support up to 5 passing points.
    params.put("tactics", ""); //Navigation policy, default is 12. Optional values: 10: no high-speed; 11: regular route, a route most people often take, which is not affected by road conditions and can be used for vehicle evaluation; 12: short distance, a relatively short route, but not necessarily a high-quality route; 13: avoid congestion 
        String result = null;
        try{
            InputStream is = httpRequestToStream(url, requestMethod, params);
            byte[] b = new byte[is.available()];
            is.read(b);
            result = new String(b);
        }catch(IOException e){
            e.printStackTrace();
        }
        if (result != null){
            JSONObject jsonObject = JSONObject.parseObject(result);
            String status_code = jsonObject.getString("statusCode");
            if (status_code == "000000"){
                // The status code is 000000, indicating that the request is successful
                System.out.println("Request successful:" + jsonObject.getString("result"));
            }else{
                // The status code is not 000000, indicating that the request failed
                System.out.println("Request failed:" + jsonObject.getString("desc"));
            }
        }else{
            // The content returned is abnormal. Sending the request failed. The following can be modified according to the business logic
            System.out.println("Send request failed");
        }
    }
}

Tags: Java JSON PHP Python

Posted on Sun, 05 Apr 2020 22:26:12 -0700 by ivalea