Goole 地图 根据经纬度获取地址

本文介绍如何使用Java实现HTTP GET请求,并结合Google Maps API获取经纬度位置对应的详细地址。

package com.jueyue;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.json.JSONException;

public class HttpRequestUtil {

public static String getRequestByUrl(String strurl){
String strjson = "";
try {
URL url = new URL(strurl);
URLConnection conn = url.openConnection();
HttpURLConnection http = (HttpURLConnection)conn;
http.setRequestMethod("GET");
http.setDoInput(true);
http.setDoOutput(true);
http.connect();
InputStream in = http.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in,"UTF-8"));
String s = null;
while((s = br.readLine()) != null) {
strjson+=s;
}
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return strjson;
}



private static HttpMethod getGetMethod(String latlng) throws IOException {
PostMethod post = new PostMethod("/maps/api/geocode/json");
GetMethod get = new GetMethod("/maps/api/geocode/json");

NameValuePair simcard = new NameValuePair("latlng", latlng);
NameValuePair simcard1 = new NameValuePair("sensor", "false");
NameValuePair simcard2 = new NameValuePair("language", "zh-CN");
get.setQueryString(new NameValuePair[] { simcard, simcard1,simcard2});

//InputStream input = new FileInputStream(new File("/home/ubuntu/my.txt"));
//"".getBytes("ISO8859-1")
//InputStream input = new StringBufferInputStream("my test aaaaaaaaaa");
//post.setRequestBody(input);
return get;
}
private static HttpMethod getPostMethod(String latlng) throws IOException {
PostMethod post = new PostMethod("/maps/api/geocode/json");

//latlng=40.714224,-73.961452&sensor=false&&language=zh-TW
NameValuePair simcard = new NameValuePair("latlng", latlng);
NameValuePair simcard1 = new NameValuePair("sensor", "false");
NameValuePair simcard2 = new NameValuePair("language", "zh-CN");

post.setRequestBody(new NameValuePair[] { simcard, simcard1,simcard2});
//InputStream input = new FileInputStream(new File("/home/ubuntu/my.txt"));
//"".getBytes("ISO8859-1")
//InputStream input = new StringBufferInputStream("my test aaaaaaaaaa");
//post.setRequestBody(input);
return post;
}

/**
* 根据经纬度获取地址
* @param latlng
* @return
*/
public static String getGoogleAddressBylatlng(String latlng){
String strAddress = "";
HttpClient client = new HttpClient();
client.getHostConfiguration().setHost("ditu.google.com", 80, "http");

HttpMethod method = null;
try {
method = getGetMethod(latlng);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}// 使用GET方式提交数据
try {
client.executeMethod(method);
} catch (HttpException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return "获取经纬度地址异常";
}
// 打印服务器返回的状态
int methodstatus = method.getStatusCode();
StringBuffer sb = new StringBuffer();
if(methodstatus == 200){
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(),"UTF-8"));
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);

}
org.json.JSONObject jo;
try {
jo = new org.json.JSONObject(sb.toString());
org.json.JSONArray ja = jo.getJSONArray("results");
org.json.JSONObject jo1 = ja.getJSONObject(0);
System.out.println(jo1.getString("formatted_address"));
strAddress = jo1.getString("formatted_address");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
rd.close();
}catch (IOException e) {
throw new RuntimeException("error", e);
}
}
method.releaseConnection();
return strAddress;
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = getRequestByUrl("http://ditu.google.com/maps/api/geocode/json?latlng=31.1899209667,121.3918055000&sensor=false&&language=zh-CN");
//String str = getRequestByUrl("http://ditu.google.com/maps/api/geocode/json?latlng=31.215912,121.477357&sensor=false&&language=zh-CN");
System.out.println(str);
/*String strhttp = HttpRequestUtil.getGoogleAddressBylatlng("31.1899209667,121.3918055000");
System.out.println(strhttp);*/
}

}

 

### 使用谷歌地图API根据地址获取经纬度 为了通过Google Maps API基于给定的地址来获得相应的地理位置坐标(即经纬度),可以采用Geocoding API。此过程涉及发送HTTP请求到指定端点并解析返回的数据以提取所需信息。 对于Python环境下的实现方式,在现代实践中推荐使用`requests`库而不是过时的`urllib2`[^4]。下面展示了一个简单的例子,说明怎样构建这样的查询: ```python import requests def get_coordinates_from_address(address): api_key = 'YOUR_API_KEY' url = f'https://maps.googleapis.com/maps/api/geocode/json?address={address}&key={api_key}' response = requests.get(url).json() if response['status'] == 'OK': location_data = response['results'][0]['geometry']['location'] lat, lng = location_data['lat'], location_data['lng'] return { "latitude": lat, "longitude": lng } else: raise Exception(f"Error fetching coordinates: {response['error_message']}") # Example usage address = "1600 Amphitheatre Parkway, Mountain View, CA" coordinates = get_coordinates_from_address(address) if coordinates is not None: print('Latitude:', coordinates["latitude"]) print('Longitude:', coordinates["longitude"]) ``` 上述代码片段展示了如何定义一个函数`get_coordinates_from_address()`,它接受一个字符串参数作为输入——该字符串代表要转换成地理坐标的物理位置描述;接着向Google Geocoding API发出GET请求,并处理JSON格式的结果以检索出具体的纬度和经度值[^3]。 值得注意的是,当实际部署这段程序之前,应当替换掉示例中的`YOUR_API_KEY`占位符为有效的Google Cloud Platform项目密钥。此外,考虑到网络延迟等因素的影响,建议加入异常捕获机制以便更好地管理可能出现的各种错误情况。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值