2013-11-23 133 views
5

我想轉換一個文本字段中包含城市名稱的文本,並將其轉換爲經度和緯度。如何從城市名稱獲取經度,緯度android代碼

這是我做了什麼:

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

我如何使用經度和緯度在我的代碼?

回答

17

通過使用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 
    } 
} 
+2

這是一個遠遠優於我提供的選項,如果Google更改JSON輸出的格式,OP將避免更新您的代碼 – mttdbrd

+0

@mttdbrd我可以使用此代碼而不是 –

+0

絕對是的 – mttdbrd

2

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

我改變的URL: 字符串myUrl =「http://maps.googleapis.com/maps/api/geocode/ ?JSON地址= 「+位置+」 &傳感器=真「; 您能否看到我的問題,我編輯了它 –

+0

我現在看到您的編輯。看到我提供的代碼。顯然,我得到的JSONObject與你得到的JSONObject不同。您可以使用JSONArray來處理結果對象。 – mttdbrd

+0

它沒有工作:( –

0

android.location.Geocoder包含方法getFromLocationName,它返回地址的列表。您可以查詢其地址以獲得其lat &長。

0
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()); 
+0

OP想要從'地點名'找到'緯度'和'經度'。你的代碼從'緯度'和'經度'給出'位置名稱'。 – Shoumik

0

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

1

爲時已晚,但對別人有同樣的問題
後第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" 
} 

所以你可以看到有一些我們需要在「位置」對象
屬性 作爲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(); 

那麼我們應該得到的經度和緯度。所以這裏是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(); 
} 

LAT1和lng1有值:)

相關問題