經緯度轉換地圖座標api支持百度、谷歌、GPS三大經緯度互相轉化。php
基於php的經緯度轉換地圖座標api調用代碼實例html
<!--?php // +---------------------------------------------------------------------- // | JuhePHP [ NO ZUO NO DIE ] // +---------------------------------------------------------------------- // | Copyright (c) 2010-2015 http://juhe.cn All rights reserved. // +---------------------------------------------------------------------- // | Author: Juhedata <info@juhe.cn--> // +---------------------------------------------------------------------- //---------------------------------- // 地圖座標服務調用示例代碼 - 聚合數據 // 在線接口文檔:http://www.juhe.cn/docs/32 //---------------------------------- header('Content-type:text/html;charset=utf-8'); //配置您申請的appkey $appkey = "*********************"; //************1.經緯度轉換************ $url = "http://v.juhe.cn/offset/index"; $params = array( "lng" => "",//經度,如:116.3974965092 "lat" => "",//緯度,如:39.908700982285396 "type" => "",//轉換類型,1:GPS->百度, 2: 百度->GPS ,3:GPS->谷歌, 4:谷歌->GPS<br/> 5:百度->谷歌 ,6:谷歌->百度 "dtype" => "",//返回數據格式:json或xml或jsonp,默認json "callback" => "",//返回格式選擇jsonp時,必須傳遞 "key" => $appkey,//你申請的key ); $paramstring = http_build_query($params); $content = juhecurl($url,$paramstring); $result = json_decode($content,true); if($result){ if($result['error_code']=='0'){ print_r($result); }else{ echo $result['error_code'].":".$result['reason']; } }else{ echo "請求失敗"; } //************************************************** /** * 請求接口返回內容 * @param string $url [請求的URL地址] * @param string $params [請求的參數] * @param int $ipost [是否採用POST形式] * @return string */ 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 , 'JuheData' ); curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 60 ); curl_setopt( $ch, CURLOPT_TIMEOUT , 60); curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true ); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 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的經緯度轉換地圖座標api調用代碼實例java
#!/usr/bin/python # -*- coding: utf-8 -*- import json, urllib from urllib import urlencode #---------------------------------- # 地圖座標服務調用示例代碼 - 聚合數據 # 在線接口文檔:http://www.juhe.cn/docs/32 #---------------------------------- def main(): #配置您申請的APPKey appkey = "*********************" #1.經緯度轉換 request1(appkey,"GET") #經緯度轉換 def request1(appkey, m="GET"): url = "http://v.juhe.cn/offset/index" params = { "lng" : "", #經度,如:116.3974965092 "lat" : "", #緯度,如:39.908700982285396 "type" : "", #轉換類型,1:GPS->百度, 2: 百度->GPS ,3:GPS->谷歌, 4:谷歌->GPS<br/> 5:百度->谷歌 ,6:谷歌->百度 "dtype" : "", #返回數據格式:json或xml或jsonp,默認json "callback" : "", #返回格式選擇jsonp時,必須傳遞 "key" : appkey, #你申請的key } 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() using System;
基於C#的經緯度轉換地圖座標api調用代碼實例python
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/32 // 代碼中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/offset/index"; var parameters1 = new Dictionary<string, string>(); parameters1.Add("lng" , ""); //經度,如:116.3974965092 parameters1.Add("lat" , ""); //緯度,如:39.908700982285396 parameters1.Add("type" , ""); //轉換類型,1:GPS->百度, 2: 百度->GPS ,3:GPS->谷歌, 4:谷歌->GPS<br/> 5:百度->谷歌 ,6:谷歌->百度 parameters1.Add("dtype" , ""); //返回數據格式:json或xml或jsonp,默認json 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); } } /// <summary> /// Http (GET/POST) /// </summary> /// <param name="url">請求URL</param> /// <param name="parameters">請求參數</param> /// <param name="method">請求方法</param> /// <returns>響應內容</returns> static string sendPost(string url, IDictionary<string, string> 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; } } /// <summary> /// 組裝普通文本請求參數。 /// </summary> /// <param name="parameters">Key-Value形式請求參數字典</param> /// <returns>URL編碼後的請求數據</returns> static string BuildQuery(IDictionary<string, string> parameters, string encode) { StringBuilder postData = new StringBuilder(); bool hasParam = false; IEnumerator<KeyValuePair<string, string>> 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(); } /// <summary> /// 把響應流轉換爲文本。 /// </summary> /// <param name="rsp">響應流對象</param> /// <param name="encoding">編碼方式</param> /// <returns>響應文本</returns> 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的經緯度轉換地圖座標api調用代碼實例
json
package main import ( "io/ioutil" "net/http" "net/url" "fmt" "encoding/json" ) //---------------------------------- // 地圖座標服務調用示例代碼 - 聚合數據 // 在線接口文檔:http://www.juhe.cn/docs/32 //---------------------------------- const APPKEY = "*******************" //您申請的APPKEY func main(){ //1.經緯度轉換 Request1() } //1.經緯度轉換 func Request1(){ //請求地址 juheURL :="http://v.juhe.cn/offset/index" //初始化參數 param:=url.Values{} //配置請求參數,方法內部已處理urlencode問題,中文參數能夠直接傳參 param.Set("lng","") //經度,如:116.3974965092 param.Set("lat","") //緯度,如:39.908700982285396 param.Set("type","") //轉換類型,1:GPS->百度, 2: 百度->GPS ,3:GPS->谷歌, 4:谷歌->GPS<br/> 5:百度->谷歌 ,6:谷歌->百度 param.Set("dtype","") //返回數據格式:json或xml或jsonp,默認json param.Set("callback","") //返回格式選擇jsonp時,必須傳遞 param.Set("key",APPKEY) //你申請的key //發送請求 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的經緯度轉換地圖座標api調用代碼實例c#
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/32 **/ 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/offset/index";//請求接口地址 Map params = new HashMap();//請求參數 params.put("lng","");//經度,如:116.3974965092 params.put("lat","");//緯度,如:39.908700982285396 params.put("type","");//轉換類型,1:GPS->百度, 2: 百度->GPS ,3:GPS->谷歌, 4:谷歌->GPS<br/> 5:百度->谷歌 ,6:谷歌->百度 params.put("dtype","");//返回數據格式:json或xml或jsonp,默認json params.put("callback","");//返回格式選擇jsonp時,必須傳遞 params.put("key",APPKEY);//你申請的key 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(Map<String,Object>data) { 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(); } }