Google Map Loading Issue In Android Listview
Solution 1:
Direct use of the mapView in a listView is a heavy operation. This is going to cause a delay and result in sluggish User Experience of your app. To avoid this behavior you have an alternative to use Static maps. This will enable Lazy Loading of maps in your list view and therby user wont have to tap map now and then.
I am providing a small example below that use this method. First create a list view from the data (Either API or DB). Then pass data such as latitude and longitude to a string with some static variables defined as follows.
StringgetMapURL="http://maps.googleapis.com/maps/api/staticmap?zoom=12&size=360x180&markers=size:mid|color:green|"
+ JOLocation.getString("latitude")
+ ","
+ JOLocation.getString("longitude")
+ "&sensor=false";
The above constructed URL, when used in a browser, returns a .PNG file. Then, in my adapter for the activity, This method results in the lazy loading of the maps in the app where your marker displaying the coordinates are fetched at runtime, avoiding heavy work in the code.
Hope this would help!!!
Solution 2:
I came across the same problem, and using your code and other stack topics I came up with this way of doing it
mapView.onCreate(savedInstanceState);
mapView.onResume();
mapView.getMapAsync(
newOnMapReadyCallback() {
@OverridepublicvoidonMapReady(GoogleMap googlemap) {
finalGoogleMapmap= googlemap;
map.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
MapsInitializer.initialize(context);
map.setMyLocationEnabled(true);
map.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
LatLngsydney=newLatLng(-33.873, 151.206);
StringmarkerTitle="Sydney";
StringsnippetTitle="Lovely city";
if (markerTitle != null && snippetTitle != null) {
map.addMarker(newMarkerOptions()
.title(markerTitle)
.snippet(snippetTitle)
.position(sydney));
}
map.setMyLocationEnabled(true);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney2, 13));
}
}
);
1) You need to call onResume(); on mapView so it loads properly 2) Use .getMapAsync, getMap is deprecated
You will be able to zoom in with a double tap :)
Solution 3:
There is a great working example by google here googlemaps sample
It loads light weight maps in a list(see LiteListDemoActivity.java in example)
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/package com.example.mapdemo;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.HashSet;
/**
* This shows to include a map in lite mode in a ListView.
* Note the use of the view holder pattern with the
* {@link com.google.android.gms.maps.OnMapReadyCallback}.
*/publicclassLiteListDemoActivityextendsAppCompatActivity {
private ListFragment mList;
private MapAdapter mAdapter;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lite_list_demo);
// Set a custom list adapter for a list of locations
mAdapter = newMapAdapter(this, LIST_LOCATIONS);
mList = (ListFragment) getSupportFragmentManager().findFragmentById(R.id.list);
mList.setListAdapter(mAdapter);
// Set a RecyclerListener to clean up MapView from ListViewAbsListViewlv= mList.getListView();
lv.setRecyclerListener(mRecycleListener);
}
/**
* Adapter that displays a title and {@link com.google.android.gms.maps.MapView} for each item.
* The layout is defined in <code>lite_list_demo_row.xml</code>. It contains a MapView
* that is programatically initialised in
* {@link #getView(int, android.view.View, android.view.ViewGroup)}
*/privateclassMapAdapterextendsArrayAdapter<NamedLocation> {
privatefinal HashSet<MapView> mMaps = newHashSet<MapView>();
publicMapAdapter(Context context, NamedLocation[] locations) {
super(context, R.layout.lite_list_demo_row, R.id.lite_listrow_text, locations);
}
@Overridepublic View getView(int position, View convertView, ViewGroup parent) {
Viewrow= convertView;
ViewHolder holder;
// Check if a view can be reused, otherwise inflate a layout and set up the view holderif (row == null) {
// Inflate view from layout file
row = getLayoutInflater().inflate(R.layout.lite_list_demo_row, null);
// Set up holder and assign it to the View
holder = newViewHolder();
holder.mapView = (MapView) row.findViewById(R.id.lite_listrow_map);
holder.title = (TextView) row.findViewById(R.id.lite_listrow_text);
// Set holder as tag for row for more efficient access.
row.setTag(holder);
// Initialise the MapView
holder.initializeMapView();
// Keep track of MapView
mMaps.add(holder.mapView);
} else {
// View has already been initialised, get its holder
holder = (ViewHolder) row.getTag();
}
// Get the NamedLocation for this item and attach it to the MapViewNamedLocationitem= getItem(position);
holder.mapView.setTag(item);
// Ensure the map has been initialised by the on map ready callback in ViewHolder.// If it is not ready yet, it will be initialised with the NamedLocation set as its tag// when the callback is received.if (holder.map != null) {
// The map is already ready to be used
setMapLocation(holder.map, item);
}
// Set the text label for this item
holder.title.setText(item.name);
return row;
}
/**
* Retuns the set of all initialised {@link MapView} objects.
*
* @return All MapViews that have been initialised programmatically by this adapter
*/public HashSet<MapView> getMaps() {
return mMaps;
}
}
/**
* Displays a {@link LiteListDemoActivity.NamedLocation} on a
* {@link com.google.android.gms.maps.GoogleMap}.
* Adds a marker and centers the camera on the NamedLocation with the normal map type.
*/privatestaticvoidsetMapLocation(GoogleMap map, NamedLocation data) {
// Add a marker for this item and set the camera
map.moveCamera(CameraUpdateFactory.newLatLngZoom(data.location, 13f));
map.addMarker(newMarkerOptions().position(data.location));
// Set the map type back to normal.
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
/**
* Holder for Views used in the {@link LiteListDemoActivity.MapAdapter}.
* Once the the <code>map</code> field is set, otherwise it is null.
* When the {@link #onMapReady(com.google.android.gms.maps.GoogleMap)} callback is received and
* the {@link com.google.android.gms.maps.GoogleMap} is ready, it stored in the {@link #map}
* field. The map is then initialised with the NamedLocation that is stored as the tag of the
* MapView. This ensures that the map is initialised with the latest data that it should
* display.
*/classViewHolderimplementsOnMapReadyCallback {
MapView mapView;
TextView title;
GoogleMap map;
@OverridepublicvoidonMapReady(GoogleMap googleMap) {
MapsInitializer.initialize(getApplicationContext());
map = googleMap;
NamedLocationdata= (NamedLocation) mapView.getTag();
if (data != null) {
setMapLocation(map, data);
}
}
/**
* Initialises the MapView by calling its lifecycle methods.
*/publicvoidinitializeMapView() {
if (mapView != null) {
// Initialise the MapView
mapView.onCreate(null);
// Set the map ready callback to receive the GoogleMap object
mapView.getMapAsync(this);
}
}
}
/**
* RecycleListener that completely clears the {@link com.google.android.gms.maps.GoogleMap}
* attached to a row in the ListView.
* Sets the map type to {@link com.google.android.gms.maps.GoogleMap#MAP_TYPE_NONE} and clears
* the map.
*/private AbsListView.RecyclerListenermRecycleListener=newAbsListView.RecyclerListener() {
@OverridepublicvoidonMovedToScrapHeap(View view) {
ViewHolderholder= (ViewHolder) view.getTag();
if (holder != null && holder.map != null) {
// Clear the map and free up resources by changing the map type to none
holder.map.clear();
holder.map.setMapType(GoogleMap.MAP_TYPE_NONE);
}
}
};
/**
* Location represented by a position ({@link com.google.android.gms.maps.model.LatLng} and a
* name ({@link java.lang.String}).
*/privatestaticclassNamedLocation {
publicfinal String name;
publicfinal LatLng location;
NamedLocation(String name, LatLng location) {
this.name = name;
this.location = location;
}
}
/**
* A list of locations to show in this ListView.
*/privatestaticfinal NamedLocation[] LIST_LOCATIONS = newNamedLocation[]{
newNamedLocation("Cape Town", newLatLng(-33.920455, 18.466941)),
newNamedLocation("Beijing", newLatLng(39.937795, 116.387224)),
newNamedLocation("Bern", newLatLng(46.948020, 7.448206)),
newNamedLocation("Breda", newLatLng(51.589256, 4.774396)),
newNamedLocation("Brussels", newLatLng(50.854509, 4.376678)),
newNamedLocation("Copenhagen", newLatLng(55.679423, 12.577114)),
newNamedLocation("Hannover", newLatLng(52.372026, 9.735672)),
newNamedLocation("Helsinki", newLatLng(60.169653, 24.939480)),
newNamedLocation("Hong Kong", newLatLng(22.325862, 114.165532)),
newNamedLocation("Istanbul", newLatLng(41.034435, 28.977556)),
newNamedLocation("Johannesburg", newLatLng(-26.202886, 28.039753)),
newNamedLocation("Lisbon", newLatLng(38.707163, -9.135517)),
newNamedLocation("London", newLatLng(51.500208, -0.126729)),
newNamedLocation("Madrid", newLatLng(40.420006, -3.709924)),
newNamedLocation("Mexico City", newLatLng(19.427050, -99.127571)),
newNamedLocation("Moscow", newLatLng(55.750449, 37.621136)),
newNamedLocation("New York", newLatLng(40.750580, -73.993584)),
newNamedLocation("Oslo", newLatLng(59.910761, 10.749092)),
newNamedLocation("Paris", newLatLng(48.859972, 2.340260)),
newNamedLocation("Prague", newLatLng(50.087811, 14.420460)),
newNamedLocation("Rio de Janeiro", newLatLng(-22.90187, -43.232437)),
newNamedLocation("Rome", newLatLng(41.889998, 12.500162)),
newNamedLocation("Sao Paolo", newLatLng(-22.863878, -43.244097)),
newNamedLocation("Seoul", newLatLng(37.560908, 126.987705)),
newNamedLocation("Stockholm", newLatLng(59.330650, 18.067360)),
newNamedLocation("Sydney", newLatLng(-33.873651, 151.2068896)),
newNamedLocation("Taipei", newLatLng(25.022112, 121.478019)),
newNamedLocation("Tokyo", newLatLng(35.670267, 139.769955)),
newNamedLocation("Tulsa Oklahoma", newLatLng(36.149777, -95.993398)),
newNamedLocation("Vaduz", newLatLng(47.141076, 9.521482)),
newNamedLocation("Vienna", newLatLng(48.209206, 16.372778)),
newNamedLocation("Warsaw", newLatLng(52.235474, 21.004057)),
newNamedLocation("Wellington", newLatLng(-41.286480, 174.776217)),
newNamedLocation("Winnipeg", newLatLng(49.875832, -97.150726))
};
}
Solution 4:
Use static map API instead of Map fragment. You can implement it using web view. First of all replace the map fragment with a webview. the follow the below steps.
Create an html file static_map.html inside html folder in asset folder
its content may be like the below
<!doctype html><html><head><metacharset="utf-8"><title>Untitled Document</title><style>html,body{
padding:0;
margin:0;
}
.map{
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
width: 100%;
height: 100%;
}
</style></head><body><imgclass="map"src="REPLACE_HERE" ></body></html>
The programmatically create a static map URL and replace REPLACE_HERE string with it. The load it on the web view. This will reduce our effort very much.
The code is as follows
try {
String url ="https://maps.googleapis.com/maps/api/staticmap?";
url+="&zoom=13";
url+="&size=600x300";
url+="&maptype=roadmap";
url+="&markers=color:green%7Clabel:G%7C"+latitude+", "+longitude;
url+="&key="+ YOUR_GOOGLE_API_KEY;
InputStream is = context.getAssets().open("html/static_map.html");
int size = is.available();
byte[] buffer = newbyte[size];
is.read(buffer);
is.close();
String str = new String(buffer);
str = str.replace("REPLACE_HERE", url);
wv_map.getSettings().setJavaScriptEnabled(true);
wv_map.loadDataWithBaseURL("", str, "text/html", "UTF-8", "");
} catch (IOException e) {
}
Need to enable and the static API in google console for this.
Post a Comment for "Google Map Loading Issue In Android Listview"