[英]Get address from latitude and longitude
我正在尝试从android中的经度和纬度获取位置地址。 我的代码如下。
public String getAddress(double latitude, double longitude) {
Geocoder myLocation = new Geocoder(this, Locale.getDefault());
List<Address> myList = null;
try {
myList = myLocation.getFromLocation(latitude,longitude,1);
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String address = myList.get(0).getAddressLine(0);
return address;
}
但是以某种方式我在myList = myLocation.getFromLocation(latitude,longitude,1);
处获得空返回值myList = myLocation.getFromLocation(latitude,longitude,1);
有什么事吗
最好,
这很常见。如果服务器未返回任何值或过载,则将为Null。
我遇到了类似的问题,并在以下帖子中找到了解决方案。
试试看,下面的代码。
try {
// Get the location manager
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
bestProvider = locationManager.getBestProvider(criteria, false);
Location location = locationManager
.getLastKnownLocation(bestProvider);
double lat = location.getLatitude();
double lon = location.getLongitude();
Geocoder gc = new Geocoder(this);
List<Address> lstAdd = gc.getFromLocation(lat, lon, 1);
Address ad = lstAdd.get(0);
String str = ad.getAddressLine(0);
Toast tst = Toast.makeText(this, "Your current location is " + str,
Toast.LENGTH_LONG);
tst.show();
} catch (Exception e) {
Toast tst = Toast.makeText(this,"Please check your gps settings",
Toast.LENGTH_LONG);
tst.show();
}
但是,当然,请尝试使用实际设备。
您可以通过google api使用,例如通过参数插入您的经度和纬度,然后将请求发送到服务器,并通过地址向服务器发送响应。
公共静态字符串getAddressUrl(Context context){字符串responseText = null;
/*String latitude="38.89";
String longitude ="-77.03";*/
Log.v(TAG , "Latitude is: " + latitude + "Longitude is:"+ longitude);
StringBuilder sbuilder=new StringBuilder();
String googleurl="http://maps.google.com/maps/geo?"
sbuilder.append(googleurl);
sbuilder.append("q="+latitude+","+longitude);
sbuilder.append("&output=responseText&sensor=true");
String url=sbuilder.toString();
Log.v(TAG, "url is: "+url);
try {
DefaultHttpClient httpclient=new DefaultHttpClient();
HttpPost httppost=new HttpPost(url);
HttpResponse httpresponse=httpclient.execute(httppost);
HttpEntity httpentity=httpresponse.getEntity();
InputStream is=httpentity.getContent();
BufferedReader reader=new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb=new StringBuilder();
String line=null;
while((line=reader.readLine())!=null)
{
sb.append(line+"\n");
}
is.close();
responseText=sb.toString();
}
catch(ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return responseText;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.