我正在使用适用于 android 的 Google Maps API v2 并且可以正常工作。 但是,我正在尝试使用地理编码器来获取地址的经度和纬度,但没有成功。
它改变了 v2 的方式?
我使用的是常规代码
Geocoder gc = new Geocoder(context);
//...
List<Address> list = gc.getFromLocationName("1600 Amphitheatre Parkway, Mountain View, CA", 1);
Address address = list.get(0);
double lat = address.getLatitude();
double lng = address.getLongitude();
//...
总是返回一个强制关闭,而 Log 什么也解决不了。 使用 try/catch block 时,打开 map 但总是在同一个位置 使用互联网权限,我在项目中也包含了COARSE_LOCATION 我使用了这里和其他网站上的各种代码,但没有成功。
提前谢谢你。
最佳答案
使用此示例 url 尝试此解决方案:
http://maps.google.com/maps/api/geocode/json?address=mumbai&sensor=false
返回json
格式的数据,lat/lng
为address
。
private class DataLongOperationAsynchTask extends AsyncTask<String, Void, String[]> {
ProgressDialog dialog = new ProgressDialog(MainActivity.this);
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setMessage("Please wait...");
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
@Override
protected String[] doInBackground(String... params) {
String response;
try {
response = getLatLongByURL("http://maps.google.com/maps/api/geocode/json?address=mumbai&sensor=false");
Log.d("response",""+response);
return new String[]{response};
} catch (Exception e) {
return new String[]{"error"};
}
}
@Override
protected void onPostExecute(String... result) {
try {
JSONObject jsonObject = new JSONObject(result[0]);
double lng = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lng");
double lat = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lat");
Log.d("latitude", "" + lat);
Log.d("longitude", "" + lng);
} catch (JSONException e) {
e.printStackTrace();
}
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
public String getLatLongByURL(String requestURL) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.setDoOutput(true);
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
response = "";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
希望对你有帮助。
关于android - 使用地理编码器和 android Google Maps API v2 获取纬度和经度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15711499/