Google Map For Android

 android.location 包提供了一些工具來實現基於位置的服務。主要包括 Geocoder 類和LocationManager服務。首先介紹 Geocoder。

1.使用Android進行地理編碼

     若是打算使用地圖作一些實際的事情,可能必須將地址(或位置)轉換爲緯度/經度對。此概念稱爲地理編碼,android.location.Geocoder 類提供了此功能。實際上,Geocoder既提供了前向轉換,也提供了後向轉換--------它能夠獲取地址並返回經度/緯度,也能夠將經度/緯度對轉換爲一組地址。該類提供瞭如下方法。
Java代碼 複製代碼
  1. List<Address>  getFromLocation(double latitude,double longitude,int maxResults);   
  2. List<Address> getFromLocationName(String locationName, int maxResults, double lowerLeftLatitude, double lowerLeftLongitue, double upperRightLatitude, double upperRightLongitude);   
  3. List<Address>  getFromLocationName(String locationName, int maxResults)。  
List<Address> getFromLocation(double latitude,double longitude,int maxResults); List<Address> getFromLocationName(String locationName, int maxResults, double lowerLeftLatitude, double lowerLeftLongitue, double upperRightLatitude, double upperRightLongitude); List<Address> getFromLocationName(String locationName, int maxResults)。List<Address> getFromLocation(double latitude,double longitude,int maxResults); List<Address> getFromLocationName(String locationName, int maxResults, double lowerLeftLatitude, double lowerLeftLongitue, double upperRightLatitude, double upperRightLongitude); List<Address> getFromLocationName(String locationName, int maxResults)。

      事實證實,計算地址並不徹底屬於科學範疇,由於能夠經過各類方式來描述位置。例如,getFromLocationName() 方法能夠得到地方的名稱、物理地址和機場編號,或者該位置的流行名稱。所以,這些方法提供了一個地址列表,而不是一個地址。由於這些方法返回一個列表,因此最好提供1~5的maxResults 值來限制結果集,下面咱們來看一個查詢地址的例子,和原來同樣咱們得本身定義一個類來繼承MapActivity,先來看看運行效果。

c306d0e8-47a1-372d-bea2-20a01b74aa1e.jpg

  咱們的佈局文件
Xml代碼 複製代碼
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent"  
  6.     >  
  7.     <LinearLayout android:layout_width="fill_parent"  
  8.         android:layout_alignParentBottom="true"  
  9.         android:layout_height="wrap_content" android:orientation="vertical">  
  10.         <EditText  
  11.             android:id="@+id/location"  
  12.             android:layout_width="fill_parent"  
  13.             android:layout_height="wrap_content"  
  14.             android:text="請輸入地址..."/>  
  15.         <Button  
  16.             android:id="@+id/geocodeBtn"  
  17.             android:layout_width="wrap_content"  
  18.             android:layout_height="wrap_content"  
  19.             android:text="Find Location" />  
  20.     </LinearLayout>  
  21.   
  22.            
  23.         <com.google.android.maps.MapView  
  24.             android:id="@+id/geoMap"  
  25.             android:clickable="true"  
  26.             android:layout_width="fill_parent"  
  27.             android:layout_height="320px"  
  28.             android:apiKey="0XemFEdFemEDqY3dE3Ko9ELJX12MRLjJGKEJ01g"  
  29.                  />  
  30.                
  31. </RelativeLayout>  
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <LinearLayout android:layout_width="fill_parent"
    	android:layout_alignParentBottom="true"
    	android:layout_height="wrap_content" android:orientation="vertical">
		<EditText
			android:id="@+id/location"
			android:layout_width="fill_parent"
			android:layout_height="wrap_content"
			android:text="請輸入地址..."/>
		<Button
			android:id="@+id/geocodeBtn"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:text="Find Location" />
    </LinearLayout>

    	
    	<com.google.android.maps.MapView
	        android:id="@+id/geoMap"
	    	android:clickable="true"
	    	android:layout_width="fill_parent"
	    	android:layout_height="320px"
	        android:apiKey="0XemFEdFemEDqY3dE3Ko9ELJX12MRLjJGKEJ01g"
                 />
            
</RelativeLayout>


  AndroidManifest.xml文件
Xml代碼 複製代碼
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="xiaohang.zhimeng" android:versionCode="1" android:versionName="1.0">  
  4.     <uses-sdk android:minSdkVersion="10" />  
  5.     <application android:icon="@drawable/icon" android:label="@string/app_name">  
  6.         <uses-library android:name="com.google.android.maps" />  
  7.         <activity android:name=".MainActivity" android:label="@string/app_name">  
  8.             <intent-filter>  
  9.                 <action android:name="android.intent.action.MAIN" />  
  10.                 <category android:name="android.intent.category.LAUNCHER" />  
  11.             </intent-filter>  
  12.         </activity>  
  13.     </application>  
  14.     <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />  
  15.     <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />  
  16.     <uses-permission android:name="android.permission.INTERNET" />  
  17. </manifest>  
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
	package="xiaohang.zhimeng" android:versionCode="1" android:versionName="1.0">
	<uses-sdk android:minSdkVersion="10" />
	<application android:icon="@drawable/icon" android:label="@string/app_name">
		<uses-library android:name="com.google.android.maps" />
		<activity android:name=".MainActivity" android:label="@string/app_name">
			<intent-filter>
				<action android:name="android.intent.action.MAIN" />
				<category android:name="android.intent.category.LAUNCHER" />
			</intent-filter>
		</activity>
	</application>
	<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
	<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
	<uses-permission android:name="android.permission.INTERNET" />
</manifest>


   咱們的MainActivity類
Java代碼 複製代碼
  1. package xiaohang.zhimeng;   
  2.   
  3. import java.util.List;   
  4.   
  5. import com.google.android.maps.GeoPoint;   
  6. import com.google.android.maps.MapActivity;   
  7. import com.google.android.maps.MapView;   
  8. import android.location.Address;   
  9. import android.location.Geocoder;   
  10. import android.os.Bundle;   
  11. import android.view.View;   
  12. import android.view.View.OnClickListener;   
  13. import android.widget.Button;   
  14. import android.widget.EditText;   
  15.   
  16. public class MainActivity extends MapActivity {   
  17.   
  18.     Geocoder geocoder = null;   
  19.     MapView mapView = null;   
  20.   
  21.     @Override  
  22.     protected boolean isLocationDisplayed() {   
  23.         return false;   
  24.     }   
  25.   
  26.     @Override  
  27.     protected boolean isRouteDisplayed() {   
  28.         return false;   
  29.     }   
  30.   
  31.     @Override  
  32.     public void onCreate(Bundle savedInstanceState) {   
  33.         super.onCreate(savedInstanceState);   
  34.         setContentView(R.layout.main);   
  35.         mapView = (MapView) findViewById(R.id.geoMap);   
  36.         mapView.setBuiltInZoomControls(true);   
  37.         // 經度:116.3946533203125   
  38.         // 緯度:39.87601941962116   
  39.         int lat = (int) (39.87601941962116 * 1E6);   
  40.         int lng = (int) (116.3946533203125 * 1E6);   
  41.         GeoPoint pt = new GeoPoint(lat, lng);   
  42.         mapView.getController().setZoom(10);   
  43.         mapView.getController().setCenter(pt);   
  44.   
  45.         Button geoBtn = (Button) findViewById(R.id.geocodeBtn);   
  46.   
  47.         geocoder = new Geocoder(this);   
  48.   
  49.         geoBtn.setOnClickListener(new OnClickListener() {   
  50.             @Override  
  51.             public void onClick(View v) {   
  52.                 try {   
  53.                     EditText loc = (EditText) findViewById(R.id.location);   
  54.                     String locationName = loc.getText().toString();   
  55.   
  56.                     List<Address> addressList = geocoder.getFromLocationName(   
  57.                             locationName, 5);   
  58.                     if (addressList != null && addressList.size() > ) {   
  59.                         int lat = (int) (addressList.get().getLatitude() * 1E6);   
  60.                         int lng = (int) (addressList.get().getLongitude() * 1E6);   
  61.   
  62.                         GeoPoint pt = new GeoPoint(lat, lng);   
  63.                         mapView.getController().setZoom(15);   
  64.                         mapView.getController().setCenter(pt);   
  65.                     }   
  66.                 } catch (Exception e) {   
  67.                     e.printStackTrace();   
  68.                 }   
  69.             }   
  70.         });   
  71.     }   
  72. }  
package xiaohang.zhimeng; import java.util.List; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapView; import android.location.Address; import android.location.Geocoder; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class MainActivity extends MapActivity { Geocoder geocoder = null; MapView mapView = null; @Override protected boolean isLocationDisplayed() { return false; } @Override protected boolean isRouteDisplayed() { return false; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mapView = (MapView) findViewById(R.id.geoMap); mapView.setBuiltInZoomControls(true); // 經度:116.3946533203125 // 緯度:39.87601941962116 int lat = (int) (39.87601941962116 * 1E6); int lng = (int) (116.3946533203125 * 1E6); GeoPoint pt = new GeoPoint(lat, lng); mapView.getController().setZoom(10); mapView.getController().setCenter(pt); Button geoBtn = (Button) findViewById(R.id.geocodeBtn); geocoder = new Geocoder(this); geoBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { try { EditText loc = (EditText) findViewById(R.id.location); String locationName = loc.getText().toString(); List<Address> addressList = geocoder.getFromLocationName( locationName, 5); if (addressList != null && addressList.size() > 0) { int lat = (int) (addressList.get(0).getLatitude() * 1E6); int lng = (int) (addressList.get(0).getLongitude() * 1E6); GeoPoint pt = new GeoPoint(lat, lng); mapView.getController().setZoom(15); mapView.getController().setCenter(pt); } } catch (Exception e) { e.printStackTrace(); } } }); } }package xiaohang.zhimeng; import java.util.List; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapView; import android.location.Address; import android.location.Geocoder; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class MainActivity extends MapActivity { Geocoder geocoder = null; MapView mapView = null; @Override protected boolean isLocationDisplayed() { return false; } @Override protected boolean isRouteDisplayed() { return false; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mapView = (MapView) findViewById(R.id.geoMap); mapView.setBuiltInZoomControls(true); // 經度:116.3946533203125 // 緯度:39.87601941962116 int lat = (int) (39.87601941962116 * 1E6); int lng = (int) (116.3946533203125 * 1E6); GeoPoint pt = new GeoPoint(lat, lng); mapView.getController().setZoom(10); mapView.getController().setCenter(pt); Button geoBtn = (Button) findViewById(R.id.geocodeBtn); geocoder = new Geocoder(this); geoBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { try { EditText loc = (EditText) findViewById(R.id.location); String locationName = loc.getText().toString(); List<Address> addressList = geocoder.getFromLocationName( locationName, 5); if (addressList != null && addressList.size() > 0) { int lat = (int) (addressList.get(0).getLatitude() * 1E6); int lng = (int) (addressList.get(0).getLongitude() * 1E6); GeoPoint pt = new GeoPoint(lat, lng); mapView.getController().setZoom(15); mapView.getController().setCenter(pt); } } catch (Exception e) { e.printStackTrace(); } } }); } }


   可是若是這個類要是這麼寫,就會有問題了。可是感受這麼寫是沒錯誤的,可是每當你點擊一次Find Location按鈕就會出現一次異常(IOException),異常見下圖。

7416da98-d708-3f9d-bdff-6173a062e108.jpg

    說什麼服務不能夠用,去網上一搜 碰見這問題的人還真很多,eoe上邊也有 可是沒說怎麼解決,不了了之了。至於爲何有這個異常,我也不能準確的告訴你們 我也不太清楚,網上說什麼的都有。 什麼 是bug之類的 等等,你們能夠去網上搜搜 最後本身這樣寫一次試試。可是解決方法仍是有的,在這裏 http://code.google.com/p/android/issues/detail?id=8816  老外搞出來的方法,他們討論的也很火熱,感受比咱們 積極不少。你們看 21樓就好了, 呵呵。

   具體解決方法就是本身定義了兩個靜態方法,我把這兩個方法放到了MapUtility類中,這個類是我本身定義的。
MapUtility類
Java代碼 複製代碼
  1. package xiaohang.zhimeng.tool;   
  2.   
  3. import java.io.IOException;   
  4. import java.io.InputStream;   
  5. import org.apache.http.HttpEntity;   
  6. import org.apache.http.HttpResponse;   
  7. import org.apache.http.client.ClientProtocolException;   
  8. import org.apache.http.client.HttpClient;   
  9. import org.apache.http.client.methods.HttpGet;   
  10. import org.apache.http.impl.client.DefaultHttpClient;   
  11. import org.json.JSONArray;   
  12. import org.json.JSONException;   
  13. import org.json.JSONObject;   
  14.   
  15. import com.google.android.maps.GeoPoint;   
  16.   
  17. public class MapUtility {   
  18.     public static JSONObject getLocationInfo(String address) {   
  19.   
  20.         HttpGet httpGet = new HttpGet("http://maps.google."  
  21.                 + "com/maps/api/geocode/json?address=" + address   
  22.                 + "ka&sensor=false");   
  23.         HttpClient client = new DefaultHttpClient();   
  24.         HttpResponse response;   
  25.         StringBuilder stringBuilder = new StringBuilder();   
  26.   
  27.         try {   
  28.             response = client.execute(httpGet);   
  29.             HttpEntity entity = response.getEntity();   
  30.             InputStream stream = entity.getContent();   
  31.             int b;   
  32.             while ((b = stream.read()) != -1) {   
  33.                 stringBuilder.append((char) b);   
  34.             }   
  35.         } catch (ClientProtocolException e) {   
  36.         } catch (IOException e) {   
  37.         }   
  38.   
  39.         JSONObject jsonObject = new JSONObject();   
  40.         try {   
  41.             jsonObject = new JSONObject(stringBuilder.toString());   
  42.         } catch (JSONException e) {   
  43.             e.printStackTrace();   
  44.         }   
  45.   
  46.         return jsonObject;   
  47.     }   
  48.   
  49.     // After executing this, another method converts that JSONObject into a   
  50.     // GeoPoint.   
  51.   
  52.     public static GeoPoint getGeoPoint(JSONObject jsonObject) {   
  53.   
  54.         Double lon = new Double();   
  55.         Double lat = new Double();   
  56.   
  57.         try {   
  58.   
  59.             lon = ((JSONArray) jsonObject.get("results")).getJSONObject()   
  60.                     .getJSONObject("geometry").getJSONObject("location")   
  61.                     .getDouble("lng");   
  62.   
  63.             lat = ((JSONArray) jsonObject.get("results")).getJSONObject()   
  64.                     .getJSONObject("geometry").getJSONObject("location")   
  65.                     .getDouble("lat");   
  66.   
  67.         } catch (JSONException e) {   
  68.             e.printStackTrace();   
  69.         }   
  70.         return new GeoPoint((int) (lat * 1E6), (int) (lon * 1E6));   
  71.     }   
  72.   
  73. }  
package xiaohang.zhimeng.tool; import java.io.IOException; import java.io.InputStream; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.google.android.maps.GeoPoint; public class MapUtility { public static JSONObject getLocationInfo(String address) { HttpGet httpGet = new HttpGet("http://maps.google." + "com/maps/api/geocode/json?address=" + address + "ka&sensor=false"); HttpClient client = new DefaultHttpClient(); HttpResponse response; StringBuilder stringBuilder = new StringBuilder(); try { response = client.execute(httpGet); HttpEntity entity = response.getEntity(); InputStream stream = entity.getContent(); int b; while ((b = stream.read()) != -1) { stringBuilder.append((char) b); } } catch (ClientProtocolException e) { } catch (IOException e) { } JSONObject jsonObject = new JSONObject(); try { jsonObject = new JSONObject(stringBuilder.toString()); } catch (JSONException e) { e.printStackTrace(); } return jsonObject; } // After executing this, another method converts that JSONObject into a // GeoPoint. public static GeoPoint getGeoPoint(JSONObject jsonObject) { Double lon = new Double(0); Double lat = new Double(0); try { lon = ((JSONArray) jsonObject.get("results")).getJSONObject(0) .getJSONObject("geometry").getJSONObject("location") .getDouble("lng"); lat = ((JSONArray) jsonObject.get("results")).getJSONObject(0) .getJSONObject("geometry").getJSONObject("location") .getDouble("lat"); } catch (JSONException e) { e.printStackTrace(); } return new GeoPoint((int) (lat * 1E6), (int) (lon * 1E6)); } }package xiaohang.zhimeng.tool; import java.io.IOException; import java.io.InputStream; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.google.android.maps.GeoPoint; public class MapUtility { public static JSONObject getLocationInfo(String address) { HttpGet httpGet = new HttpGet("http://maps.google." + "com/maps/api/geocode/json?address=" + address + "ka&sensor=false"); HttpClient client = new DefaultHttpClient(); HttpResponse response; StringBuilder stringBuilder = new StringBuilder(); try { response = client.execute(httpGet); HttpEntity entity = response.getEntity(); InputStream stream = entity.getContent(); int b; while ((b = stream.read()) != -1) { stringBuilder.append((char) b); } } catch (ClientProtocolException e) { } catch (IOException e) { } JSONObject jsonObject = new JSONObject(); try { jsonObject = new JSONObject(stringBuilder.toString()); } catch (JSONException e) { e.printStackTrace(); } return jsonObject; } // After executing this, another method converts that JSONObject into a // GeoPoint. public static GeoPoint getGeoPoint(JSONObject jsonObject) { Double lon = new Double(0); Double lat = new Double(0); try { lon = ((JSONArray) jsonObject.get("results")).getJSONObject(0) .getJSONObject("geometry").getJSONObject("location") .getDouble("lng"); lat = ((JSONArray) jsonObject.get("results")).getJSONObject(0) .getJSONObject("geometry").getJSONObject("location") .getDouble("lat"); } catch (JSONException e) { e.printStackTrace(); } return new GeoPoint((int) (lat * 1E6), (int) (lon * 1E6)); } }


   這兩個方法就很少解釋了,反正咱們最終的目的是須要一個GeoPoint對象,它給咱們返回正確的GeoPoint對象就好了,你們能夠去原地址去看看他們怎麼討論了,連接在上邊我已經貼出來了,如今咱們在搜索tian an men 就會把tian an men給咱們顯示在地圖的中央了,沒修改以前是 一點 一次異常,如今的效果以下圖,( 你們知道 tian an men是啥意思吧,自動eye被 oracle搞過一次 法律意識愈來愈強啊。。。。  icon_evil.gif )

db6a58c9-0552-3651-9d2f-e4c7932c414a.jpg

     要體驗地理編碼在Android中的使用,能夠在 EditText字段中鍵入位置名稱或它的地址,而後點擊 Find Location按鈕。要找到某個位置的地址,調用 Geocoder的 getFromLocationName()方法。位置能夠是地址或流行名稱,好比 「故宮」。地理編碼是一項實時操做,因此根據Android文檔的建議,咱們建議將結果限制爲5個。對getFromLocationName()的調用返回一個地址列表。示例程序獲取該地址列表並處理第一個地址(若是存在)。每一個地址都具備經緯度。可使用它來建立 GeoPoint。而後調用地圖控制器並導航到該點。縮放級別能夠設置爲1~21 (包括1和21)的整數。在從1向21移動時,縮放級別每次將增長兩級。

      對於地理編碼,應該瞭解幾點。第一,返回的地址並不老是準確的地址。顯然,因爲返回的地址列表取決於輸入的準確度,因此須要儘可能向 Geocoder 提供準確的位置名稱。第二,儘可能將 maxResults 設置爲1~5的值。最後,應該認真考慮在不一樣於UI線程的線程中執行地理編碼操做。這有兩個緣由。第一個很明顯:這項操做很耗時,並且你必定不但願UI在進行地理編碼時停頓,若是停頓會阻塞整個用戶界面。當在執行一些耗時的操做的時候,不能及時地分發 事件,包括用戶界面重繪事件。從用戶的角度來看,應用程序看上去像掛掉了。更糟糕的是,若是阻塞應用程序的時間過長(5秒鐘)Android會向用戶提示 一些信息,即打開一個「應用程序沒有相應(application not responding)」ANR 的對話框,關於線程的更多內容請你們看這裏 http://byandby.iteye.com/blog/825071  第二個緣由是,對於移動設備,始終須要假設網絡鏈接可能丟失而且鏈接很弱。所以,須要恰當地處理I/O 異常和超時。計算出地址之後,就能夠將結果發送給UI線程,下面咱們看看使用後臺線程進行地理編碼,這個例子和上一個例子同樣 惟一不一樣的就是 這個例子把查詢地址的操做放到 另一個輔助線程裏來執行了,上一個是全部的操做都在UI線程裏,下面是咱們的Activity類,GeocodingDemoActivity,咱們看看怎麼實現。。。

  GeocodingDemoActivity類
Java代碼 複製代碼
  1. package xiaohang.zhimeng;   
  2.   
  3. import java.util.List;   
  4. import org.json.JSONObject;   
  5. import xiaohang.zhimeng.tools.MapUtility;   
  6. import android.app.AlertDialog;   
  7. import android.app.Dialog;   
  8. import android.app.ProgressDialog;   
  9. import android.location.Address;   
  10. import android.location.Geocoder;   
  11. import android.os.Bundle;   
  12. import android.os.Handler;   
  13. import android.os.Message;   
  14. import android.view.View;   
  15. import android.view.View.OnClickListener;   
  16. import android.widget.Button;   
  17. import android.widget.EditText;   
  18. import com.google.android.maps.GeoPoint;   
  19. import com.google.android.maps.MapActivity;   
  20. import com.google.android.maps.MapView;   
  21.   
  22. public class GeocodingDemoActivity extends MapActivity {   
  23.   
  24.     Geocoder geocoder = null;   
  25.     MapView mapView = null;   
  26.     ProgressDialog progDialog = null;   
  27.     List<Address> addressList = null;   
  28.   
  29.     @Override  
  30.     protected boolean isLocationDisplayed() {   
  31.         return false;   
  32.     }   
  33.   
  34.     @Override  
  35.     protected boolean isRouteDisplayed() {   
  36.         return false;   
  37.     }   
  38.   
  39.     @Override  
  40.     protected void onCreate(Bundle icicle) {   
  41.         super.onCreate(icicle);   
  42.         setContentView(R.layout.main);   
  43.         mapView = (MapView) findViewById(R.id.geoMap);   
  44.         mapView.setBuiltInZoomControls(true);   
  45.         // 北京經緯度   
  46.         // 經度:116.3946533203125   
  47.         // 緯度:39.87601941962116   
  48.         int lat = (int) (39.87601941962116 * 1000000);   
  49.         int lng = (int) (116.3946533203125 * 1000000);   
  50.         GeoPoint pt = new GeoPoint(lat, lng);   
  51.         mapView.getController().setZoom(10);   
  52.         mapView.getController().setCenter(pt);   
  53.   
  54.         Button geoBtn = (Button) findViewById(R.id.geocodeBtn);   
  55.         geoBtn.setOnClickListener(new OnClickListener() {   
  56.             @Override  
  57.             public void onClick(View v) {   
  58.                 EditText loc = (EditText) findViewById(R.id.location);   
  59.                 String locationName = loc.getText().toString();   
  60.                 progDialog = ProgressDialog.show(GeocodingDemoActivity.this,   
  61.                         "Processing.....""Finding Location"truefalse);   
  62.                 findLocation(locationName);   
  63.   
  64.             }   
  65.         });   
  66.     }   
  67.   
  68.     private void findLocation(final String locationName) {   
  69.   
  70.         Thread thrd = new Thread() {   
  71.             @Override  
  72.             public void run() {   
  73.                 System.out.println("線程Name是:"  
  74.                         + Thread.currentThread().getName());   
  75.                 try {   
  76.                     // do backgrond work   
  77.                     JSONObject jo = MapUtility.getLocationInfo(locationName);   
  78.                     GeoPoint gp = MapUtility.getGeoPoint(jo);   
  79.                     Message message = uiCallback.obtainMessage();   
  80.                     message.obj = gp;   
  81.                     message.sendToTarget();   
  82.                 } catch (Exception e) {   
  83.                     e.printStackTrace();   
  84.                 }   
  85.             }   
  86.         };   
  87.         thrd.start();   
  88.     }   
  89.   
  90.     // ui thread callback handler   
  91.     private Handler uiCallback = new Handler() {   
  92.         public void handleMessage(android.os.Message msg) {   
  93.             System.out.println("線程Name是:" + Thread.currentThread().getName());   
  94.             progDialog.dismiss();   
  95.             GeoPoint pt = (GeoPoint) msg.obj;   
  96.             if (pt != null) {   
  97.                 mapView.getController().setZoom(15);   
  98.                 mapView.getController().setCenter(pt);   
  99.             } else {   
  100.                 Dialog foundNothingDlg = new AlertDialog.Builder(   
  101.                         GeocodingDemoActivity.this).setIcon()   
  102.                         .setTitle("Failed to Find Location")   
  103.                         .setPositiveButton("OK"null)   
  104.                         .setMessage("Location Not Found").create();   
  105.                 foundNothingDlg.show();   
  106.             }   
  107.         };   
  108.     };   
  109. }  
package xiaohang.zhimeng; import java.util.List; import org.json.JSONObject; import xiaohang.zhimeng.tools.MapUtility; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.location.Address; import android.location.Geocoder; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapView; public class GeocodingDemoActivity extends MapActivity { Geocoder geocoder = null; MapView mapView = null; ProgressDialog progDialog = null; List<Address> addressList = null; @Override protected boolean isLocationDisplayed() { return false; } @Override protected boolean isRouteDisplayed() { return false; } @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); mapView = (MapView) findViewById(R.id.geoMap); mapView.setBuiltInZoomControls(true); // 北京經緯度 // 經度:116.3946533203125 // 緯度:39.87601941962116 int lat = (int) (39.87601941962116 * 1000000); int lng = (int) (116.3946533203125 * 1000000); GeoPoint pt = new GeoPoint(lat, lng); mapView.getController().setZoom(10); mapView.getController().setCenter(pt); Button geoBtn = (Button) findViewById(R.id.geocodeBtn); geoBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { EditText loc = (EditText) findViewById(R.id.location); String locationName = loc.getText().toString(); progDialog = ProgressDialog.show(GeocodingDemoActivity.this, "Processing.....", "Finding Location", true, false); findLocation(locationName); } }); } private void findLocation(final String locationName) { Thread thrd = new Thread() { @Override public void run() { System.out.println("線程Name是:" + Thread.currentThread().getName()); try { // do backgrond work JSONObject jo = MapUtility.getLocationInfo(locationName); GeoPoint gp = MapUtility.getGeoPoint(jo); Message message = uiCallback.obtainMessage(); message.obj = gp; message.sendToTarget(); } catch (Exception e) { e.printStackTrace(); } } }; thrd.start(); } // ui thread callback handler private Handler uiCallback = new Handler() { public void handleMessage(android.os.Message msg) { System.out.println("線程Name是:" + Thread.currentThread().getName()); progDialog.dismiss(); GeoPoint pt = (GeoPoint) msg.obj; if (pt != null) { mapView.getController().setZoom(15); mapView.getController().setCenter(pt); } else { Dialog foundNothingDlg = new AlertDialog.Builder( GeocodingDemoActivity.this).setIcon(0) .setTitle("Failed to Find Location") .setPositiveButton("OK", null) .setMessage("Location Not Found").create(); foundNothingDlg.show(); } }; }; }package xiaohang.zhimeng; import java.util.List; import org.json.JSONObject; import xiaohang.zhimeng.tools.MapUtility; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.location.Address; import android.location.Geocoder; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapView; public class GeocodingDemoActivity extends MapActivity { Geocoder geocoder = null; MapView mapView = null; ProgressDialog progDialog = null; List<Address> addressList = null; @Override protected boolean isLocationDisplayed() { return false; } @Override protected boolean isRouteDisplayed() { return false; } @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); mapView = (MapView) findViewById(R.id.geoMap); mapView.setBuiltInZoomControls(true); // 北京經緯度 // 經度:116.3946533203125 // 緯度:39.87601941962116 int lat = (int) (39.87601941962116 * 1000000); int lng = (int) (116.3946533203125 * 1000000); GeoPoint pt = new GeoPoint(lat, lng); mapView.getController().setZoom(10); mapView.getController().setCenter(pt); Button geoBtn = (Button) findViewById(R.id.geocodeBtn); geoBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { EditText loc = (EditText) findViewById(R.id.location); String locationName = loc.getText().toString(); progDialog = ProgressDialog.show(GeocodingDemoActivity.this, "Processing.....", "Finding Location", true, false); findLocation(locationName); } }); } private void findLocation(final String locationName) { Thread thrd = new Thread() { @Override public void run() { System.out.println("線程Name是:" + Thread.currentThread().getName()); try { // do backgrond work JSONObject jo = MapUtility.getLocationInfo(locationName); GeoPoint gp = MapUtility.getGeoPoint(jo); Message message = uiCallback.obtainMessage(); message.obj = gp; message.sendToTarget(); } catch (Exception e) { e.printStackTrace(); } } }; thrd.start(); } // ui thread callback handler private Handler uiCallback = new Handler() { public void handleMessage(android.os.Message msg) { System.out.println("線程Name是:" + Thread.currentThread().getName()); progDialog.dismiss(); GeoPoint pt = (GeoPoint) msg.obj; if (pt != null) { mapView.getController().setZoom(15); mapView.getController().setCenter(pt); } else { Dialog foundNothingDlg = new AlertDialog.Builder( GeocodingDemoActivity.this).setIcon(0) .setTitle("Failed to Find Location") .setPositiveButton("OK", null) .setMessage("Location Not Found").create(); foundNothingDlg.show(); } }; }; }


   此次咱們再來看看運行效果。

cbf0ad1c-d80b-31ce-a630-0c18aae32126.jpg

7da308b7-7f8f-3fc5-bafd-8356bee25dfe.jpg

530d3218-02e4-3755-8232-0f50b32d47a1.jpg

   從下圖咱們能看出 查詢操做在不一樣的線程中完成。

5cbd789e-aaa2-32cc-902f-458efe0f48a2.jpg

  最後在提醒你們若是下載源碼 注意替換成本身的 密鑰。

轉載於:https://my.oschina.net/yl1988/blog/33030android