2014-10-01 47 views
1

Im正在將標記加載到谷歌地圖,它的性能非常差:加載地圖和40個標記需要大約5秒(在地圖和標記加載之前,屏幕空白)如何加載android谷歌地圖標記更快?

這是我的xml文件:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
       xmlns:tools="http://schemas.android.com/tools" 
       android:layout_width="match_parent" 
       android:layout_height="match_parent"> 
    <fragment 
      android:id="@+id/map" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      class="com.google.android.gms.maps.SupportMapFragment"/> 
</RelativeLayout> 

下面的代碼添加標記到地圖:

1)遍歷所有餐廳的對象,每個餐廳獲得地址。

2)將地址經緯度對象

3)添加使用方法AsyncTaskonPostExecute添加標記,以標記

 //partial of the method 
     for (Restaurant rest : rests) { 
      LatLng ll = getLatLng(rest.getAddress());//converts address to LatLng 
      MarkerOptions marker = new MarkerOptions() 
        .title(rest.getName()) 
//     .snippet("Briefly description: " + i++) 
        .position(ll) 
        .icon(BitmapDescriptorFactory.fromResource(R.drawable.marker)) 
        .anchor(0.0f, 1.0f); 
      myMap.addMarker(marker); 
     } 


     public LatLng getLatLng(String address) { 

     try { 
      ArrayList<Address> addresses = (ArrayList<Address>) geocoder.getFromLocationName(address, MAX_ADDRESS_ALLOWDED); 
      for (Address add : addresses) { 
       if (true) {//Controls to ensure it is right address such as country etc. 
        longitude = add.getLongitude(); 
        latitude = add.getLatitude(); 
       } 
      } 
     } catch (Exception e) { 
      Toast.makeText(myContext, e.getMessage(), Toast.LENGTH_SHORT).show(); 
     } 
     return new LatLng(latitude, longitude); 
    } 

IM,誰能幫助我?

+1

我會建議緩存每個地址的經度和緯度,以防止每次加載它們。地理編碼器請求會阻止並可能需要相當長時間。 – kcoppock 2014-10-02 00:14:34

回答

0

AsyncTask的onPostExecute方法在主UI線程中運行。這就是爲什麼(如果你已經嘗試過),你可以從Post創建一個Toast,但不能從後臺線程中執行。基本上你想通過從你的主要活動中抽出一些來平衡負荷。特別是儘量保持循環在後臺。使用新的線程並將標記與Handler放在一起。

public void placeMarkers(final ArrayList<String>myArray, final Handler handler){ 
    new Thread(){ 
     @Override 
     public void run(){ 
     //my for loops 
      for(int i = 0; i < myArray.size(); i++){ 
       //post with a handler.. 

       handler.post(new Runnable() { 
        @Override 
        public void run() { 
         //place your markers. 
        } 
       }); 
      } 
      //etc etc.. 
     } 
    }.run(); 
} 

另一種方法是使用你的主題,你的MainActivity從而消除了處理器的需要之間的接口..

1

而且把標記在不同的文件夾繪製圖標(華電國際,MDPI ,. ..)而不是一個文件夾(可繪製)可能會有所幫助。我的意思是讓圖標與不同的屏幕分辨率兼容。