使用百度地图API获取经纬度

来源:互联网 发布:python fix 编辑:程序博客网 时间:2024/05/17 03:54

注意事项:
1. 使用 百度地图API 需要先申请 ak(API 密钥)。

事例 java 代码如下:
package test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import net.sf.json.JSONObject;

public class TestBaiduMapAPI {

/** * description: This method was used to get longitude and latitude.  * @param address */public static void test(String address){    // address: 地址      output:输出格式     ak:是申请的百度 api 密钥    String path = "http://api.map.baidu.com/geocoder/v2/?address="+address+"&output=json&ak=####################";    String lineData = null;    StringBuilder sb = new StringBuilder();    try {        URL url = new URL(path);        URLConnection conn = url.openConnection();        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));        while((lineData = br.readLine()) != null){            sb.append(lineData);        }        JSONObject json = JSONObject.fromObject(sb.toString());        JSONObject result = json.getJSONObject("result").getJSONObject("location");        String lng = result.getString("lng");        String lat = result.getString("lat");        System.out.println("coordinate:("+lng+", "+ lat+");");    } catch (MalformedURLException e) {        // TODO Auto-generated catch block        e.printStackTrace();    } catch (IOException e) {        // TODO Auto-generated catch block        e.printStackTrace();    }}public static void main(String[] args) {    test("中国江苏省连云港市");}

}

0 0
原创粉丝点击