基站定位是指手机发射基站根据与手机的距离来计算手机坐标地理位置的一种功能,基站定位一般应用于手机用户,手机基站定位服务又叫做移动位置服务(LBS服务),它是通过电信移动运营商的网络(如GSM网)获取移动终端用户的位置信息(经纬度坐标),在电子地图平台的支持下,为用户提供相应服务的一种增值业务。
LBS基站定位接口支持基站定位,通过移动联通基站的CID和LAC进行基站位置查询。
接口名称:LBS基站定位接口
接口平台:聚合数据
接口地址:http://v.juhe.cn/cell/get
支持格式:json/xml
请求方式:get/post
请求示例:http://v.juhe.cn/cell/get?mnc=0&cell=28655&lac=17695&key=您申请的APPKEY
JSON返回示例:
{
"resultcode":"200",
"reason":"Return Successd!",
"result":{
"data":[
{
"MCC":"460",
"MNC":"1",
"LNG":"120.721423",
"LAT":"31.29854",
"O_LNG":"120.72577772352",
"O_LAT":"31.296529947917",
"PRECISION":"1101",
"ADDRESS":"江苏省苏州市吴中区金鸡湖大道368号"
}
]
}
}
XML返回示例:
200
Return Successd!
-
460
1
120.721423
31.29854
120.72577772352
31.296529947917
1101
江苏省苏州市吴中区金鸡湖大道368号
示例代码
基于PHP的移动LBS基站定位接口调用代码实例
本代码是基于聚合数据的移动联通基站查询API实现的基站定位功能,使用前需要:
一、通过http://www.juhe.cn/docs/api/id/8申请一个接口查询appkey
二、完整调用代码实例:
// +----------------------------------------------------------------------
//----------------------------------
// 聚合数据-基站查询API调用示例代码
//----------------------------------
header('Content-type:text/html;charset=utf-8');
$apiurl = 'http://v.juhe.cn/cell/get'; //基站接口url
$mnc = '0';//移动基站:0 联通基站:1 默认:0
$cell = '28655';//大区号
$lac = '17695';//小区号
$key = '52a0ee009932b35054********'; //您申请的appkey
$params = "mnc={$mnc}&cell={$cell}&lac={$lac}&key={$key}";
$content = juhecurl($apiurl,$params);
if(!$content){
echo "网络错误,请求接口失败";
}else{
$result = json_decode($content,true);
$error_code = $result['error_code'];
if($error_code == 0){
//成功请求到数据
$data = $result['result']['data'][0];
/*
"MCC":"460",
"MNC":"1",
"LNG":"120.721423", //gps坐标:经度
"LAT":"31.29854", //gps坐标:纬度
"O_LNG":"120.72577772352", //高德坐标:经度
"O_LAT":"31.296529947917", //高德坐标:纬度
"PRECISION":"1101", //基站覆盖半径
"ADDRESS":"江苏省苏州市吴中区金鸡湖大道368号" //基站地址
*/
print_r($data);
}else{
echo $result['reason']."(".$result['error_code'].")";
}
}
function juhecurl($url,$params=false,$ispost=0){
$httpInfo = array();
$ch = curl_init();
curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
curl_setopt( $ch, CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36' );
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 30 );
curl_setopt( $ch, CURLOPT_TIMEOUT , 30);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
if( $ispost )
{
curl_setopt( $ch , CURLOPT_POST , true );
curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
curl_setopt( $ch , CURLOPT_URL , $url );
}
else
{
if($params){
curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
}else{
curl_setopt( $ch , CURLOPT_URL , $url);
}
}
$response = curl_exec( $ch );
if ($response === FALSE) {
//echo "cURL Error: " . curl_error($ch);
return false;
}
$httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
$httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
curl_close( $ch );
return $response;
}
基于Python的移动LBS基站定位接口调用代码实例
#!/usr/bin/python
# -*- coding: utf-8 -*-
import json, urllib
from urllib import urlencode
#----------------------------------
# 移动联通基站调用示例代码 - 聚合数据
# 在线接口文档:http://www.juhe.cn/docs/8
#----------------------------------
def main():
#配置您申请的APPKey
appkey = "*********************"
#1.基站定位
request1(appkey,"GET")
#基站定位
def request1(appkey, m="GET"):
url = "http://v.juhe.cn/cell/get"
params = {
"mnc" : "", #移动基站:0 联通基站:1 默认:0
"lac" : "", #小区号
"cell" : "", #基站号
"hex" : "", #进制类型,16或10,默认:10
"dtype" : "", #返回的数据格式:json/xml/jsonp
"callback" : "", #当选择jsonp格式时必须传递
"key" : appkey, #APPKEY
}
params = urlencode(params)
if m =="GET":
f = urllib.urlopen("%s?%s" % (url, params))
else:
f = urllib.urlopen(url, params)
content = f.read()
res = json.loads(content)
if res:
error_code = res["error_code"]
if error_code == 0:
#成功请求
print res["result"]
else:
print "%s:%s" % (res["error_code"],res["reason"])
else:
print "request api error"
if __name__ == '__main__':
main()
基于C#的移动LBS基站定位接口调用代码实例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using Xfrog.Net;
using System.Diagnostics;
using System.Web;
//----------------------------------
// 移动联通基站调用示例代码 - 聚合数据
// 在线接口文档:http://www.juhe.cn/docs/8
// 代码中JsonObject类下载地址:http://download.csdn.net/download/gcm3206021155665/7458439
//----------------------------------
namespace ConsoleAPI
{
class Program
{
static void Main(string[] args)
{
string appkey = "*******************"; //配置您申请的appkey
//1.基站定位
string url1 = "http://v.juhe.cn/cell/get";
var parameters1 = new Dictionary();
parameters1.Add("mnc" , ""); //移动基站:0 联通基站:1 默认:0
parameters1.Add("lac" , ""); //小区号
parameters1.Add("cell" , ""); //基站号
parameters1.Add("hex" , ""); //进制类型,16或10,默认:10
parameters1.Add("dtype" , ""); //返回的数据格式:json/xml/jsonp
parameters1.Add("callback" , ""); //当选择jsonp格式时必须传递
parameters1.Add("key", appkey);//你申请的key
string result1 = sendPost(url1, parameters1, "get");
JsonObject newObj1 = new JsonObject(result1);
String errorCode1 = newObj1["error_code"].Value;
if (errorCode1 == "0")
{
Debug.WriteLine("成功");
Debug.WriteLine(newObj1);
}
else
{
//Debug.WriteLine("失败");
Debug.WriteLine(newObj1["error_code"].Value+":"+newObj1["reason"].Value);
}
}
///
/// Http (GET/POST)
///
/// 请求URL
/// 请求参数
/// 请求方法
/// 响应内容
static string sendPost(string url, IDictionary parameters, string method)
{
if (method.ToLower() == "post")
{
HttpWebRequest req = null;
HttpWebResponse rsp = null;
System.IO.Stream reqStream = null;
try
{
req = (HttpWebRequest)WebRequest.Create(url);
req.Method = method;
req.KeepAlive = false;
req.ProtocolVersion = HttpVersion.Version10;
req.Timeout = 5000;
req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
byte[] postData = Encoding.UTF8.GetBytes(BuildQuery(parameters, "utf8"));
reqStream = req.GetRequestStream();
reqStream.Write(postData, 0, postData.Length);
rsp = (HttpWebResponse)req.GetResponse();
Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
return GetResponseAsString(rsp, encoding);
}
catch (Exception ex)
{
return ex.Message;
}
finally
{
if (reqStream != null) reqStream.Close();
if (rsp != null) rsp.Close();
}
}
else
{
//创建请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + "?" + BuildQuery(parameters, "utf8"));
//GET请求
request.Method = "GET";
request.ReadWriteTimeout = 5000;
request.ContentType = "text/html;charset=UTF-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
//返回内容
string retString = myStreamReader.ReadToEnd();
return retString;
}
}
///
/// 组装普通文本请求参数。
///
/// Key-Value形式请求参数字典
/// URL编码后的请求数据
static string BuildQuery(IDictionary parameters, string encode)
{
StringBuilder postData = new StringBuilder();
bool hasParam = false;
IEnumerator> dem = parameters.GetEnumerator();
while (dem.MoveNext())
{
string name = dem.Current.Key;
string value = dem.Current.Value;
// 忽略参数名或参数值为空的参数
if (!string.IsNullOrEmpty(name))//&& !string.IsNullOrEmpty(value)
{
if (hasParam)
{
postData.Append("&");
}
postData.Append(name);
postData.Append("=");
if (encode == "gb2312")
{
postData.Append(HttpUtility.UrlEncode(value, Encoding.GetEncoding("gb2312")));
}
else if (encode == "utf8")
{
postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8));
}
else
{
postData.Append(value);
}
hasParam = true;
}
}
return postData.ToString();
}
///
/// 把响应流转换为文本。
///
/// 响应流对象
/// 编码方式
/// 响应文本
static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
{
System.IO.Stream stream = null;
StreamReader reader = null;
try
{
// 以字符流的方式读取HTTP响应
stream = rsp.GetResponseStream();
reader = new StreamReader(stream, encoding);
return reader.ReadToEnd();
}
finally
{
// 释放资源
if (reader != null) reader.Close();
if (stream != null) stream.Close();
if (rsp != null) rsp.Close();
}
}
}
}
基于GO的移动LBS基站定位接口调用代码实例
package main
import (
"io/ioutil"
"net/http"
"net/url"
"fmt"
"encoding/json"
)
//----------------------------------
// 移动联通基站调用示例代码 - 聚合数据
// 在线接口文档:http://www.juhe.cn/docs/8
//----------------------------------
const APPKEY = "*******************" //您申请的APPKEY
func main(){
//1.基站定位
Request1()
}
//1.基站定位
func Request1(){
//请求地址
juheURL :="http://v.juhe.cn/cell/get"
//初始化参数
param:=url.Values{}
//配置请求参数,方法内部已处理urlencode问题,中文参数可以直接传参
param.Set("mnc","") //移动基站:0 联通基站:1 默认:0
param.Set("lac","") //小区号
param.Set("cell","") //基站号
param.Set("hex","") //进制类型,16或10,默认:10
param.Set("dtype","") //返回的数据格式:json/xml/jsonp
param.Set("callback","") //当选择jsonp格式时必须传递
param.Set("key",APPKEY) //APPKEY
//发送请求
data,err:=Get(juheURL,param)
if err!=nil{
fmt.Errorf("请求失败,错误信息:\r\n%v",err)
}else{
var netReturn map[string]interface{}
json.Unmarshal(data,&netReturn)
if netReturn["error_code"].(float64)==0{
fmt.Printf("接口返回result字段是:\r\n%v",netReturn["result"])
}
}
}
// get 网络请求
func Get(apiURL string,params url.Values)(rs[]byte ,err error){
var Url *url.URL
Url,err=url.Parse(apiURL)
if err!=nil{
fmt.Printf("解析url错误:\r\n%v",err)
return nil,err
}
//如果参数中有中文参数,这个方法会进行URLEncode
Url.RawQuery=params.Encode()
resp,err:=http.Get(Url.String())
if err!=nil{
fmt.Println("err:",err)
return nil,err
}
defer resp.Body.Close()
return ioutil.ReadAll(resp.Body)
}
// post 网络请求 ,params 是url.Values类型
func Post(apiURL string, params url.Values)(rs[]byte,err error){
resp,err:=http.PostForm(apiURL, params)
if err!=nil{
return nil ,err
}
defer resp.Body.Close()
return ioutil.ReadAll(resp.Body)
}
基于JAVA的移动LBS基站定位接口调用代码实例
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONObject;
/**
*移动联通基站调用示例代码 - 聚合数据
*在线接口文档:http://www.juhe.cn/docs/8
**/
public class JuheDemo {
public static final String DEF_CHATSET = "UTF-8";
public static final int DEF_CONN_TIMEOUT = 30000;
public static final int DEF_READ_TIMEOUT = 30000;
public static String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
//配置您申请的KEY
public static final String APPKEY ="*************************";
//1.基站定位
public static void getRequest1(){
String result =null;
String url ="http://v.juhe.cn/cell/get";//请求接口地址
Map params = new HashMap();//请求参数
params.put("mnc","");//移动基站:0 联通基站:1 默认:0params.put("lac","");//小区号
params.put("cell","");//基站号
params.put("hex","");//进制类型,16或10,默认:10
params.put("dtype","");//返回的数据格式:json/xml/jsonp
params.put("callback","");//当选择jsonp格式时必须传递
params.put("key",APPKEY);//APPKEY
try {
result =net(url, params, "GET");
JSONObject object = JSONObject.fromObject(result);
if(object.getInt("error_code")==0){
System.out.println(object.get("result"));
}else{
System.out.println(object.get("error_code")+":"+object.get("reason"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
}
/**
*
* @param strUrl 请求地址
* @param params 请求参数
* @param method 请求方法
* @return 网络请求字符串
* @throws Exception
*/
public static String net(String strUrl, Map params,String method) throws Exception {
HttpURLConnection conn = null;
BufferedReader reader = null;
String rs = null;
try {
StringBuffer sb = new StringBuffer();
if(method==null || method.equals("GET")){
strUrl = strUrl+"?"+urlencode(params);
}
URL url = new URL(strUrl);
conn = (HttpURLConnection) url.openConnection();
if(method==null || method.equals("GET")){
conn.setRequestMethod("GET");
}else{
conn.setRequestMethod("POST");
conn.setDoOutput(true);
}
conn.setRequestProperty("User-agent", userAgent);
conn.setUseCaches(false);
conn.setConnectTimeout(DEF_CONN_TIMEOUT);
conn.setReadTimeout(DEF_READ_TIMEOUT);
conn.setInstanceFollowRedirects(false);
conn.connect();
if (params!= null && method.equals("POST")) {
try {
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(urlencode(params));
} catch (Exception e) {
// TODO: handle exception
}
}
InputStream is = conn.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sb.append(strRead);
}
rs = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
if (conn != null) {
conn.disconnect();
}
}
return rs;
}
//将map型转为请求参数型
public static String urlencode(Mapdata) {
StringBuilder sb = new StringBuilder();
for (Map.Entry i : data.entrySet()) {
try {
sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}