如何从城市名称中获取经度、纬度的android代码

如何从城市名称中获取经度、纬度的android代码,android,Android,我想转换从包含城市名称的文本字段中提取的文本,并将其转换为经度和纬度 这是我做的: String location=city.getText().toString(); String inputLine = ""; String result = ""; location=location.replaceAll(" ", "%20"); String myUrl="http://maps.google

我想转换从包含城市名称的文本字段中提取的文本,并将其转换为经度和纬度

这是我做的:

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更改为:

字符串myUrl=”http://maps.googleapis.com/maps/api/geocode/json?address=“+位置+”&传感器=真”

这就是结果:

{
   "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"
}

如何在代码中使用纬度和经度???

使用新的API,您将返回一个JSON对象。与其将其解析为字符串,不如将其解析为JSON对象。下面是(最后)为您提供的JSON字符串编译并返回正确值的代码

try
{
    org.json.JSONObject jso = new JSONObject(result);
    org.json.JSONArray jsa = jso.getJSONArray("results");
    org.json.JSONObject js2 = jsa.getJSONObject(0);
    org.json.JSONObject js3 = js2.getJSONObject("geometry");
    org.json.JSONObject js4 = js3.getJSONObject("location");
    Double lat = (Double)js4.getDouble("lat");
    Double lng = (Double)js4.getDouble("lng");

}
catch(JSONException jse)
{
    jse.printStackTrace();
}

有一种更简单的方法是使用。它的功能与地理编码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
    }
}
if(Geocoder.isPresent()){
试一试{
String location=“theNameofLocation”;
地理编码器gc=新地理编码器(本);
List addresses=gc.getFromLocationName(位置,5);//获取找到的地址对象
List ll=new ArrayList(addresses.size());//保存坐标(如果坐标可用)的列表
地址(地址a:地址){
if(a.hasLatitude()&&a.hasLatitude()){
ll.add(新LatLng(a.getLatitude(),a.getLongitude());
}  
}  
}捕获(IOE异常){
//处理异常
}
}

android.location.Geocoder
包含一个方法
getFromLocationName
,该方法返回地址列表。您可以查询其lat&long地址。

Geocoder gcd=new Geocoder(context,Locale.getDefault());
Geocoder gcd = new Geocoder(context, Locale.getDefault());
List<Address> addresses = gcd.getFromLocation(lat, lng, 1);
if (addresses.size() > 0) 
    System.out.println(addresses.get(0).getLocality());
列表地址=gcd.getFromLocation(lat,lng,1); 如果(地址.size()>0) System.out.println(addresses.get(0.getLocality());
公共静态LatLng GetCitylize(上下文,字符串城市){
Geocoder Geocoder=新的地理编码器(context,context.getResources().getConfiguration().locale);
列表地址=空;
LatLng LatLng=null;
试一试{
地址=地理编码器。getFromLocationName(城市,1);
地址=地址。获取(0);
latLng=新latLng(address.getLatitude(),address.getLongitude());
}捕获(例外e){
e、 printStackTrace();
}
返回板条;

}

为时已晚,但对于其他有同样问题的人来说
4天后,我从城市名称中获得了经度和纬度

我曾经

http://maps.googleapis.com/maps/api/geocode/json?address=tehran&sensor=false
其中,“德黑兰”是城市名称

通过此链接,您可以获得如下所示的json

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "Tehran",
               "short_name" : "Tehran",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Tehran",
               "short_name" : "Tehran",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Tehran Province",
               "short_name" : "Tehran Province",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "Iran",
               "short_name" : "IR",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "Tehran, Tehran Province, Iran",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 35.8345498,
                  "lng" : 51.6062163
               },
               "southwest" : {
                  "lat" : 35.5590784,
                  "lng" : 51.0934209
               }
            },
            "location" : {
               "lat" : 35.6891975,
               "lng" : 51.3889736
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 35.8345498,
                  "lng" : 51.6062163
               },
               "southwest" : {
                  "lat" : 35.5590784,
                  "lng" : 51.0934209
               }
            }
         },
         "place_id" : "ChIJ2dzzH0kAjj8RvCRwVnxps_A",
         "types" : [ "locality", "political" ]
      }
   ],
   "status" : "OK"
}
如您所见,在“位置”对象中有我们需要的属性
如前所述,我们需要从顶级URL获取Json
因此,我们很容易添加JsonTask

private class JsonTask extends AsyncTask<String, String, String> {

    protected void onPreExecute() {
        super.onPreExecute();
        // u can use a dialog here
    }

    protected String doInBackground(String... params) {


        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();


            InputStream stream = connection.getInputStream();

            reader = new BufferedReader(new InputStreamReader(stream));

            StringBuffer buffer = new StringBuffer();
            String line = "";

            while ((line = reader.readLine()) != null) {
                buffer.append(line+"\n");
                Log.d("Response: ", "> " + line);   //here u ll get whole response...... :-) 

            }

            return buffer.toString();


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        // here "result" is json as stting
    }
}
}
然后我们应该得到经度和纬度。这就是我们需要的s.th

JSONObject jsonResponse1;
try {
    jsonResponse1 = new JSONObject(jsonMap1);
    JSONArray cast = jsonResponse1.getJSONArray("results");
    for (int i = 0; i < cast.length(); i++) {
        JSONObject actor = cast.getJSONObject(i);
        JSONObject name = actor.getJSONObject("geometry");
        JSONObject location = name.getJSONObject("location");
        lat1 = location.getString("lat");
        lng1 = location.getString("lng");
    }
} catch (JSONException e) {
    Toast.makeText(mContext, e.toString(), Toast.LENGTH_SHORT).show();
}
JSONObject jsonResponse1;
试一试{
jsonResponse1=新的JSONObject(jsonMap1);
JSONArray cast=jsonResponse1.getJSONArray(“结果”);
对于(int i=0;i

lat1和lng1的值为:)

I将URL更改为:String myUrl=“”;你能看到我的问题吗?我编辑了它。我现在看到你的编辑。请参阅我提供的代码。显然,我得到的JSONObject与你得到的不同。您可以使用JSONArray来处理results对象。我会用你得到的数据让它工作。但是请看下面@steve的答案,它比我提供的方法要好得多。这是一个比我提供的方法要好得多的选项,我认为,如果Google更改JSON输出的格式,OP将不必更新您的代码。OP想要
纬度
经度
来自
位置名
。您的代码从
纬度
经度
中给出
位置名
JSONObject jsonResponse1;
try {
    jsonResponse1 = new JSONObject(jsonMap1);
    JSONArray cast = jsonResponse1.getJSONArray("results");
    for (int i = 0; i < cast.length(); i++) {
        JSONObject actor = cast.getJSONObject(i);
        JSONObject name = actor.getJSONObject("geometry");
        JSONObject location = name.getJSONObject("location");
        lat1 = location.getString("lat");
        lng1 = location.getString("lng");
    }
} catch (JSONException e) {
    Toast.makeText(mContext, e.toString(), Toast.LENGTH_SHORT).show();
}