我想转换从包含城市名称的文本字段中获取的文本,我想将其转换为经度和纬度。
这是我做的:
String location=city.getText().toString();
String inputLine = "";
String result = "";
location=location.replaceAll(" ", "%20");
String myUrl="http://maps.google.com/maps/geo?q="+location+"&output=csv";
try{
URL url=new URL(myUrl);
URLConnection urlConnection=url.openConnection();
BufferedReader in = new BufferedReader(new
InputStreamReader(urlConnection.getInputStream()));
while ((inputLine = in.readLine()) != null) {
result=inputLine;
}
lat = result.substring(6, result.lastIndexOf(","));
longi = result.substring(result.lastIndexOf(",") + 1);
}
catch(Exception e){
e.printStackTrace();
}
//////////////////////////////////
if (location=="" )
{
latitude=loc.getLatitude();
longitude=loc.getLongitude();
}
else
{
latitude=Double.parseDouble(lat);
longitude=Double.parseDouble(longi);
}
但是代码没有采用else语句
我将 URL 更改为:
String myUrl="http://maps.googleapis.com/maps/api/geocode/json?address="+location+"&sensor=true";
这是结果:
{
"results" : [
{
"address_components" : [
{
"long_name" : "Nablus",
"short_name" : "Nablus",
"types" : [ "locality", "political" ]
}
],
"formatted_address" : "Nablus",
"geometry" : {
"location" : {
"lat" : 32.22504,
"lng" : 35.260971
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 32.2439165,
"lng" : 35.2929858
},
"southwest" : {
"lat" : 32.20615960000001,
"lng" : 35.2289562
}
}
},
"types" : [ "locality", "political" ]
}
],
"status" : "OK"
}
如何在我的代码中使用纬度和经度?
最佳答案
使用 Geocoder 有一个更简单的方法.它的作用与地理编码 API 几乎相同。
if(Geocoder.isPresent()){
try {
String location = "theNameOfTheLocation";
Geocoder gc = new Geocoder(this);
List<Address> addresses= gc.getFromLocationName(location, 5); // get the found Address Objects
List<LatLng> ll = new ArrayList<LatLng>(addresses.size()); // A list to save the coordinates if they are available
for(Address a : addresses){
if(a.hasLatitude() && a.hasLongitude()){
ll.add(new LatLng(a.getLatitude(), a.getLongitude()));
}
}
} catch (IOException e) {
// handle the exception
}
}
关于android - 如何从城市名称android代码获取经度,纬度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20166328/