【问题标题】:how to get longitude,latitude from the city name android code如何从城市名称android代码中获取经度,纬度
【发布时间】:2013-11-23 18:41:48
【问题描述】:

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

这是我做的:

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语句

我把网址改成了这样:

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

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

【问题讨论】:

    标签: android


    【解决方案1】:

    使用Geocoder 有一种更简单的方法。它的作用与 Geocoding 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
        }
    }
    

    【讨论】:

    • 这比我提供的选项要好得多,我认为如果 Google 更改 JSON 输出的格式,OP 将避免更新您的代码。
    【解决方案2】:

    为时已晚,但对于其他有同样问题的人
    4 天后,我从城市名称中得到 longitudelatitude

    我用过

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

    如您所见,“位置”对象中有我们需要的属性
    正如this answer 一开始所说,我们需要从顶级 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
        }
    }
    }
    

    要调用和保存 JSON 字符串,您需要此代码

    JsonTask getRequest = new JsonTask();
    String JSONString = getRequest.execute("Url address here").get();
    

    那么我们应该得到经度和纬度。所以这是我们需要的某事

    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();
    }
    

    lat1 和 lng1 具有值:)

    【讨论】:

      【解决方案3】:

      使用新的 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();
      }
      

      【讨论】:

      • 我把网址改成了:String myUrl="maps.googleapis.com/maps/api/geocode/…";你能看到我的问题吗,我编辑了它
      • 我现在看到了您的编辑。请参阅我提供的代码。显然,我得到的 JSONObject 与你得到的不同。您可以使用 JSONArray 来处理结果对象。
      • 正如我所指出的,我返回了一组不同的数据。我将使它与您获得的一组数据一起工作。但是请参阅下面@steve 的答案,这比使用我提供的方法要好得多。
      【解决方案4】:

      android.location.Geocoder 包含一个方法getFromLocationName,它返回一个地址列表。您可以查询地址的经纬度。

      【讨论】:

        【解决方案5】:
        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());
        

        【讨论】:

        • OP 想要 latitudelongitude 来自 location name。您的代码从latitudelongitude 给出location name
        【解决方案6】:

        public static LatLng getCityLatitude(Context context, String city) { Geocoder geocoder = new Geocoder(context,context.getResources().getConfiguration().locale); List<Address> addresses = null; LatLng latLng = null; try { addresses = geocoder.getFromLocationName(city, 1); Address address = addresses.get(0); latLng = new LatLng(address.getLatitude(), address.getLongitude()); } catch (Exception e) { e.printStackTrace(); } return latLng; }

        【讨论】:

          猜你喜欢
          • 2013-12-09
          • 1970-01-01
          • 1970-01-01
          • 2011-09-26
          • 1970-01-01
          • 2013-03-03
          • 2017-10-07
          • 2014-04-14
          相关资源
          最近更新 更多