Reputation: 31925
Im loading markers to google map and it has really bad performace: it takes about 5 seconds to load the map and 40 markers.(Before the map and markers load, the screen is blank)
Here's my xml file:
<?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>
The following code is adding markers to the map:
1) iterate all Restaurant objects, gets address for each restaurant.
2) converts address to LatLng objects
3) add to marker
//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 using method onPostExecute
of AsyncTask
for adding markers, can anyone help me?
Upvotes: 1
Views: 1498
Reputation: 475
Also putting markers' icons in different drawable folders(hdpi,mdpi,...) instead of one folder(drawable) could be helpful. I mean making icons compatible with different screen resolutions.
Upvotes: 1
Reputation: 200
The onPostExecute method of a AsyncTask runs in the Main UI thread. Which is why (if you've tried) you can make a Toast from the Post execute but not from the Background thread. Basically you want to even out the load by taking some of it off of your main activity. Especially try to keep loops in the background. Use a new Thread and place the markers with a 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();
}
Another way would to be to use a interface between your Thread and your MainActivity thus removing the need for a handler..
Upvotes: 0