I want to display multiple markers on google map v2 and also on tap animate marker with a jump animation.
/**
* This shows how to place markers on a map.
*/
public class Map extends FragmentActivity implements
OnMarkerClickListener,
OnInfoWindowClickListener,
OnMarkerDragListener {
static LatLng[] GEOPOINTS;
Map con;
ArrayList<Article> mArticles;
DBHelper helper;
Drawable marker;
Button search, cancel;
EditText search_value;
Button clear_search;
int activity_flag=0;
double slat, vlong;
/**
* Demonstrates customizing the info window and/or its contents.
*/
class CustomInfoWindowAdapter implements InfoWindowAdapter {
private final RadioGroup mOptions;
// These a both viewgroups containing an ImageView with id "badge" and two TextViews with id
// "title" and "snippet".
private final View mWindow;
private final View mContents;
CustomInfoWindowAdapter() {
mWindow = getLayoutInflater().inflate(R.layout.custom_info_window, null);
mContents = getLayoutInflater().inflate(R.layout.custom_info_contents, null);
mOptions = (RadioGroup) findViewById(R.id.custom_info_window_options);
}
#Override
public View getInfoWindow(Marker marker) {
if (mOptions.getCheckedRadioButtonId() != R.id.custom_info_window) {
// This means that getInfoContents will be called.
return null;
}
render(marker, mWindow);
return mWindow;
}
#Override
public View getInfoContents(Marker marker) {
if (mOptions.getCheckedRadioButtonId() != R.id.custom_info_contents) {
// This means that the default info contents will be used.
return null;
}
render(marker, mContents);
return mContents;
}
private void render(Marker marker, View view) {
int badge;
badge = R.drawable.badge_qld;
((ImageView) view.findViewById(R.id.badge)).setImageResource(badge);
String title = marker.getTitle();
TextView titleUi = ((TextView) view.findViewById(R.id.title));
if (title != null) {
// Spannable string allows us to edit the formatting of the text.
SpannableString titleText = new SpannableString(title);
titleText.setSpan(new ForegroundColorSpan(Color.RED), 0, titleText.length(), 0);
titleUi.setText(titleText);
} else {
titleUi.setText("");
}
String snippet = marker.getSnippet();
TextView snippetUi = ((TextView) view.findViewById(R.id.snippet));
if (snippet != null && snippet.length() > 12) {
SpannableString snippetText = new SpannableString(snippet);
snippetText.setSpan(new ForegroundColorSpan(Color.MAGENTA), 0, 10, 0);
snippetText.setSpan(new ForegroundColorSpan(Color.BLUE), 12, snippet.length(), 0);
snippetUi.setText(snippetText);
} else {
snippetUi.setText("");
}
}
}
private GoogleMap mMap;
private Marker[] marks;
private TextView mTopText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.marker_demo);
con=this;
mTopText = (TextView) findViewById(R.id.top_text);
new loadingTask().execute();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map wrap the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getPolarisMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
// Hide the zoom controls as the button panel will cover it.
mMap.getUiSettings().setZoomControlsEnabled(false);
// Add lots of markers to the map.
addMarkersToMap();
// Setting an info window adapter allows us to change the both the contents and look of the
// info window.
mMap.setInfoWindowAdapter(new CustomInfoWindowAdapter());
// Set listeners for marker events. See the bottom of this class for their behavior.
mMap.setOnMarkerClickListener(this);
mMap.setOnInfoWindowClickListener(this);
mMap.setOnMarkerDragListener(this);
// Pan to see all markers in view.
// Cannot zoom to bounds until the map has a size.
final View mapView = getSupportFragmentManager().findFragmentById(R.id.map).getView();
if (mapView.getViewTreeObserver().isAlive()) {
mapView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#SuppressWarnings("deprecation") // We use the new method when supported
#SuppressLint("NewApi") // We check which build version we are using.
#Override
public void onGlobalLayout() {
LatLngBounds bounds = new LatLngBounds.Builder().include(GEOPOINTS[0]).build();
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
mapView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
} else {
mapView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 50));
}
});
}
}
private void addMarkersToMap() {
// Uses a colored icon.
for (int i=0;i<mArticles.size();i++){
String latt=mArticles.get(i).latitude.trim().replace(",","");
String lonn=mArticles.get(i).longitude.trim();
//set latitude and longitude
GEOPOINTS[i] = new LatLng(Double.valueOf(latt), Double.valueOf(lonn));
marks[i] = mMap.addMarker(new MarkerOptions()
.position(GEOPOINTS[i])
.title(mArticles.get(i).enseigne)
.snippet(mArticles.get(i).type)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.arrow)));
}
}
private boolean checkReady() {
if (mMap == null) {
Toast.makeText(this, R.string.map_not_ready, Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
/**
* Called when the Clear button is clicked.
*/
public void onClearMap(View view) {
if (!checkReady()) {
return;
}
mMap.clear();
}
/**
* Called when the Reset button is clicked.
*/
public void onResetMap(View view) {
if (!checkReady()) {
return;
}
// Clear the map because we don't want duplicates of the markers.
mMap.clear();
addMarkersToMap();
}
//
// Marker related listeners.
//
#Override
public boolean onMarkerClick(final Marker marker) {
// This causes the marker at Perth to bounce into position when it is clicked.
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
Projection proj = mMap.getProjection();
Point startPoint = proj.toScreenLocation(GEOPOINTS[0]);
startPoint.offset(0, -100);
final LatLng startLatLng = proj.fromScreenLocation(startPoint);
final long duration = 1500;
final Interpolator interpolator = new BounceInterpolator();
handler.post(new Runnable() {
#Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float) elapsed / duration);
double lng = t * GEOPOINTS[0].longitude + (1 - t) * startLatLng.longitude;
double lat = t * GEOPOINTS[0].latitude + (1 - t) * startLatLng.latitude;
marker.setPosition(new LatLng(lat, lng));
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
}
}
});
// We return false to indicate that we have not consumed the event and that we wish
// for the default behavior to occur (which is for the camera to move such that the
// marker is centered and for the marker's info window to open, if it has one).
return false;
}
#Override
public void onInfoWindowClick(Marker marker) {
Toast.makeText(getBaseContext(), "Click Info Window", Toast.LENGTH_SHORT).show();
}
#Override
public void onMarkerDragStart(Marker marker) {
mTopText.setText("onMarkerDragStart");
}
#Override
public void onMarkerDragEnd(Marker marker) {
mTopText.setText("onMarkerDragEnd");
}
#Override
public void onMarkerDrag(Marker marker) {
mTopText.setText("onMarkerDrag. Current Position: " + marker.getPosition());
}
class loadingTask extends AsyncTask<Void, Void,Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
setUpMapIfNeeded();
}
#Override
protected Void doInBackground(Void... params) {
helper = DBHelper.getInstance(con);
mArticles = helper.getArticlesList();
System.out.println(mArticles.toString());
return null;
}
}
}
But my log shows the following error.
java.lang.RuntimeException: Unable to resume activity
{com.example.test/com.example.test.Map}: java.lang.NullPointerException
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2698)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2726)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2212)
at android.app.ActivityThread.access$600(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4899)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.test.Map.addMarkersToMap(Map.java:233)
at com.example.test.Map.setUpMap(Map.java:197)
at com.example.test.Map.setUpMapIfNeeded(Map.java:187)
at com.example.test.Map.onResume(Map.java:177)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1184)
at android.app.Activity.performResume(Activity.java:5082)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2688)
... 12 more
I have two problems, the first one is to display multiple geopoints and the second is to make each marker to jump on tap. can anyone help me.
Update: New Logs after changing onResume()
java.lang.NullPointerException
at com.example.test.Map$1.onGlobalLayout(Map.java:217)
at android.view.ViewTreeObserver.dispatchOnGlobalLayout(ViewTreeObserver.java:646)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1726)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4214)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
at android.view.Choreographer.doCallbacks(Choreographer.java:555)
at android.view.Choreographer.doFrame(Choreographer.java:525)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4899)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
at dalvik.system.NativeStart.main(Native Method)
Where line 217 is
LatLngBounds bounds = new LatLngBounds.Builder().include(GEOPOINTS[0]).build();
you are getting NullPointerException because mArticles is null when you call setUpMapIfNeeded(); in onResume()
So
Change
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
to
#Override
protected void onResume() {
super.onResume();
new loadingTask().execute();
}
Edit :
your GEOPOINTS[0] is null at line no 217
LatLngBounds bounds = new LatLngBounds.Builder().include(GEOPOINTS[0]).build();
Reason
you have problem inside private void addMarkersToMap(), you are not initializing GEOPOINTS, so initialize GEOPOINT before for loop, for this use : GEOPOINTS=new LatLng[mArticles.size()];
So it Should look like :
GEOPOINTS=new LatLng[mArticles.size()];
for (int i=0;i<mArticles.size();i++){
String latt=mArticles.get(i).latitude.trim().replace(",","");
String lonn=mArticles.get(i).longitude.trim();
//set latitude and longitude
GEOPOINTS[i] = new LatLng(Double.valueOf(latt), Double.valueOf(lonn));
Related
I'm using google map in my application ,when I click the marker info-window is opened again I want to click the info-window layout but its not working for layouts.If I give click listener for button means its working.Please help me to fix this issue.
Activity:
public class SampleFragment1 extends Fragment implements OnMapReadyCallback,GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener, LocationListener {
private ViewGroup infoWindow;
private TextView infoTitle;
private TextView infoSnippet,userNameTV,loggedLabel,userLastNameTV,time,distance,tasks;
private Button infoButton, infoButton2;
private OnInfoWindowElemTouchListener infoButtonListener;
LinearLayout markerlay;
GoogleMap mMap;
public void createLocationRequest() {
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
}
private MapView mapView;
private MarkerOptions mMarker;
MapWrapperLayout mapWrapperLayout;
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View view = inflater.inflate(R.layout.con_fragment_google, container, false);
mapWrapperLayout = (MapWrapperLayout)view.findViewById(R.id.map_relative_layout);
mapView = (MapView)view. findViewById(R.id.mapView);
// getContext().startService(new Intent(getContext(),GPSTracker.class));
mapView.onCreate(savedInstanceState);
buildGoogleApiClient();
createLocationRequest();
mapView.getMapAsync(this);
return view;
}
private synchronized void buildGoogleApiClient() {
try {
mGoogleApiClient = new GoogleApiClient.Builder(getContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
// to get current latitude and longitude
// storing the updated latitde and longitude when user moving and reach destination
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mapWrapperLayout.init(mMap, getPixelsFromDp(getContext(), 39 + 20));
// We want to reuse the info window for all the markers,
// so let's create only one class member instance
this.infoWindow = (ViewGroup)getActivity().getLayoutInflater().inflate(R.layout.info_widow_layout, null);
this.infoTitle = (TextView)infoWindow.findViewById(R.id.nametv);
this.infoSnippet = (TextView)infoWindow.findViewById(R.id.addressTv);
this.infoButton = (Button)infoWindow.findViewById(R.id.clinicType);
// Setting custom OnTouchListener which deals with the pressed state
// so it shows up
this.infoButtonListener = new OnInfoWindowElemTouchListener(infoTitle
) //btn_default_pressed_holo_light
{
#Override
protected void onClickConfirmed(View v, Marker marker) {
// Here we can perform some action triggered after clicking the button
Toast.makeText(getContext(), marker.getTitle() + "'s button clicked!", Toast.LENGTH_SHORT).show();
}
};
this.infoTitle.setOnTouchListener(infoButtonListener);
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
// Setting up the infoWindow with current's marker info
infoTitle.setText(marker.getTitle());
infoSnippet.setText(marker.getSnippet());
infoButtonListener.setMarker(marker);
// We must call this to set the current marker and infoWindow references
// to the MapWrapperLayout
mapWrapperLayout.setMarkerWithInfoWindow(marker, infoWindow);
return infoWindow;
}
});
// Let's add a couple of markers
}
public static int getPixelsFromDp(Context context, float dp) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dp * scale + 0.5f);
}
}
Note:Here I give click listener for textview ,the textview present inside the layout.
I want to load images asynchronously and show them on the infowindow. For this I made a custom class to store parameters. I need for this (marker, image) but my code throws a runtime exception saying it can't call getPosition on the marker I stored in the custom class instance.
What is the correct way to use AsyncTask with custom class instance parameters?
This is my code:
googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
LatLng latLng = marker.getPosition();
// find location id in database
Location location = dbhandler.getLocationByLatLng(latLng);
final int id = location.getId();
addButton.setVisibility(View.VISIBLE);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// open load image fragment
android.support.v4.app.FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
LoadImageFragment fragment = new LoadImageFragment();
// pass id to new fragment
Bundle bundle = new Bundle();
bundle.putInt("id", id);
fragment.setArguments(bundle);
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
});
removeButton.setVisibility(View.VISIBLE);
removeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// remove markers and images
}
});
class TaskParams {
Marker marker;
Location location;
Image image;
TaskParams() {
}
public Location getLocation() {
return this.location;
}
public Marker getMarker() {
return this.marker;
}
public Image getImage(){
return this.image;
}
public void setMarker(Marker marker) {
this.marker = marker;
}
public void setLocation(Location location) {
this.location = location;
}
public void setImage(Image image) {
this.image = image;
}
}
TaskParams taskParams = new TaskParams();
taskParams.setMarker(marker);
new AsyncTask<TaskParams, Void, TaskParams>() {
#Override
protected TaskParams doInBackground(TaskParams... params) {
TaskParams tParams = params[0];
Marker m = tParams.getMarker();
LatLng latLng = m.getPosition();
Location location = dbhandler.getLocationByLatLng(latLng);
tParams.setLocation(location);
return tParams;
}
// find image and text associated with Location
protected void onPostExecute(TaskParams taskParams) {
new AsyncTask<TaskParams, Void, TaskParams>() {
#Override
protected TaskParams doInBackground(TaskParams... params) {
TaskParams tParams = params[0];
Location location = tParams.getLocation();
try {
image = dbhandler.getImageByLocationId(location.getId());
tParams.setImage(image);
}
catch (Exception ex){
Log.d("debug", "failed to fetch image");
image = null;
}
return tParams;
}
#Override
protected void onPostExecute(TaskParams taskParams) {
Image image = taskParams.getImage();
// set image and description
if(image != null) {
infoImageView.setImageBitmap(image.getBitmap());
infoTextView.setText(image.getDescription());
Marker marker = taskParams.getMarker();
marker.showInfoWindow();
updateInfoWindow(image);
}
}
}.execute(taskParams);
}
}.execute(taskParams);
//marker.showInfoWindow();
return true;
}
});
// find Location in database
// Setting a custom info window adapter for the google map
googleMap.setInfoWindowAdapter(new InfoWindowAdapter() {
// Use default InfoWindow frame
#Override
public View getInfoWindow(Marker arg0) {
return null;
}
// Defines the contents of the InfoWindow
#Override
public View getInfoContents(Marker arg0) {
// Getting view from the layout file info_window_layout
View v = getActivity().getLayoutInflater().inflate(R.layout.info_window_layout, null);
// Getting the position from the marker
final LatLng latLng = arg0.getPosition();
infoImageView = (ImageView) v.findViewById(R.id.infoImage);
infoTextView = (TextView) v.findViewById(R.id.infoText);
if(image != null) {
infoImageView.setImageBitmap(image.getBitmap());
infoTextView.setText(image.getDescription());
}
return v;
}
});
You can override the constructor. Something like:
private class MyAsyncTask extends AsyncTask<Void, Void, Void> {
public MyAsyncTask(boolean showLoading) {
super();
// do stuff
}
// doInBackground() et al.
}
Then, when calling the task, do something like:
new MyAsyncTask(true).execute(maybe_other_params);
This is more useful than creating member variables because it simplifies the task invocation. Compare the code above with:
MyAsyncTask task = new MyAsyncTask();
task.showLoading = false;
task.execute();
I have main activity with fragments and one of the fragments is Map Fragment. Now, when i tap there, every time it opens slow. I am using singleton instance of fragment, but it still doesnt work as expected. Here is a good of that class:
public MapsFragment() {
gson = new Gson();
}
public static MapsFragment getInstance() {
if (mInstance == null)
mInstance = new MapsFragment();
return mInstance;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable final Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.fragment_maps, container, false);
mOnSavedinstance = savedInstanceState;
mMapView = (MapView) v.findViewById(R.id.map);
mMapWrapperLayout = (MapWrapperLayout) v.findViewById(R.id.map_relative_layout);
mMapView.getMapAsync(MapsFragment.this);
mMapView.onCreate(savedInstanceState);
mMapView.requestFocus();
MapsInitializer.initialize(getActivity());
return v;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
// MapWrapperLayout initialization
// 39 - default marker height
// 20 - offset between the default InfoWindow bottom edge and it's content bottom edge
mMapWrapperLayout.init(mGoogleMap, Constants.MARKER_HEIGHT);
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
mGoogleMap.setMyLocationEnabled(false);
}
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
setUpMap();
}
private void setUpMap() {
new Thread(new Runnable() {
#Override
public void run() {
final ArrayList<MarkerOptions> markerOptionses = new ArrayList<MarkerOptions>();
int counter = 0;
for (final Places places : Model.getInstance().getPlaces()) {
LatLng location = new LatLng(Double.parseDouble(places.getLat()), Double.parseDouble(places.getLon()));
final MarkerOptions options = new MarkerOptions();
options.snippet(gson.toJson(places));
options.position(location);
options.title(String.valueOf(counter));
markerOptionses.add(options);
counter++;
}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
for (MarkerOptions markerOptionse : markerOptionses) {
mGoogleMap.addMarker(markerOptionse).setIcon(BitmapDescriptorFactory.fromResource(Model.getInstance().getPlaces()
.get(Integer.parseInt(markerOptionse.getTitle())).getMapsRes(getActivity())));
}
}
});
final CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(45.4654, 9.1859)) // Sets the center of the map to location user
.zoom(Constants.CAMERA_ZOOM_LOCATION) // Sets the zoom
.build(); // Creates a CameraPosition from the builder
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mGoogleMap.setOnMapClickListener(MapsFragment.this);
// mGoogleMap.setOnInfoWindowClickListener(mInfoListener);
}
});
}
}).start();
}
#Override
public void onResume() {
mMapView.onResume();
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
mGoogleMap.clear();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
You can try to add markers only if it would be visible? I mean: first move camera to start position and set zoomLevel and just after that add Markers but only if it's in visible sector. And update markers on camera move.
I am working on map application Android and try use AlphaSeekBar to my polygons on Google Maps v2 Android.
I try to use that SeekBar working on my all polygons, but it turns out just working on last polygon.
This is my code:
private static final int ALPHA_MAX = 255;
private SeekBar mAlphaBar;
private Polygon mMutablePolygon;
private GoogleMap mMap;
.........................................
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kabupaten);
mAlphaBar = (SeekBar) findViewById(R.id.alphaSeekBar);
mAlphaBar.setMax(ALPHA_MAX);
mAlphaBar.setProgress(127);
mMessageView = (TextView) findViewById(R.id.message_text);
setUpMapIfNeeded();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
mMap.setMyLocationEnabled(true);
mMap.setPadding(currentLeft, currentTop, currentRight, currentBottom);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(DR, 14));
// poligon area --
{
PolygonOptions options = new PolygonOptions()
.add(dr_1,dr_2,dr_3,dr_4,dr_5,dr_6,dr_7,dr_8,dr_9,dr_10,dr_11,dr_12,dr_13,dr_14,dr_15,dr_16,dr_17) ;
mMutablePolygon = mMap.addPolygon(options
.strokeColor(Color.RED)
.strokeWidth(1)
.fillColor(Color.CYAN));
PolygonOptions gt =new PolygonOptions()
.add(gt_1,gt_2,gt_3,gt_4,gt_5,gt_6,gt_7,gt_8,gt_9,gt_10,gt_11,gt_12,gt_13,gt_14,gt_15,gt_16) ;
mMutablePolygon = mMap.addPolygon(gt
.strokeColor(Color.RED)
.strokeWidth(1)
.fillColor(Color.GREEN));
mAlphaBar.setOnSeekBarChangeListener(this);
}
// Add a camera change listener.
mMap.setOnCameraChangeListener(new OnCameraChangeListener() {
public void onCameraChange(CameraPosition pos) {
mMessageView.setText("CameraChangeListener: " + pos);
}
});
}
}
}
public void onStopTrackingTouch(SeekBar seekBar) {
// Don't do anything here.
}
public void onStartTrackingTouch(SeekBar seekBar) {
// Don't do anything here.
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (mMutablePolygon == null) {
return;
}
if (seekBar == mAlphaBar) {
int prevColor = mMutablePolygon.getFillColor();
mMutablePolygon.setFillColor(Color.argb(
progress, Color.red(prevColor), Color.green(prevColor),
Color.blue(prevColor)));
}
}
}
The problem is that you are keeping just one reference to polygon
If you want to update all of them, you need to use a List mMutablePolygons;
Then when each polygon is created:
mPolygon = mMap.addPolygon(options
.strokeColor(Color.RED)
.strokeWidth(1)
.fillColor(Color.CYAN));
mMutablePolygons.add(mPolygon);
and when changing the seekbar value:
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (mMutablePolygons == null || mMutablePolygons.isEmpty()) {
return;
}
if (seekBar == mAlphaBar) {
for(Polygon mpoly : mMutablePolygons){
int prevColor = mpoly.getFillColor();
mpoly.setFillColor(Color.argb(progress, Color.red(prevColor), Color.green(prevColor),Color.blue(prevColor)));
}
}
}
I have a strange problem with a com.google.android.gms.maps.MapView.
To check if my App crashes after the garbage collector is doing his job i force my HTC One (4.2.2) to allow only 1 running app in background. If I leave my app(home button) while showing a MapView, start any other app and resume to my app, my MapView is still showing up...but I can not move or zoom the map, it's not responding at all. Other activities are working fine. I really have no clue where the problem might be.
Hope that someone can help me out?
Here is the sourcecode of my fragment that shows the MapView
public class FragmentAdvertlistMap extends Fragment {
com.google.android.gms.maps.MapView m;
GoogleMap mMap;
ArrayList<Advert> ads;
HashMap<Marker, String> myMarker;
public final LatLngBounds.Builder builder= new LatLngBounds.Builder();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
try {
MapsInitializer.initialize(getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
// TODO handle this situation
}
View inflatedView = inflater.inflate(R.layout.activity_advert_tab2, container, false);
m = (com.google.android.gms.maps.MapView)inflatedView.findViewById(R.id.map_tab);
m.onCreate(savedInstanceState);
myMarker = new HashMap<Marker, String>();
ads= AdvertListActivity.getAdverts();
setUpMapIfNeeded(inflatedView);
mMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker arg0) {
Intent myIntent = new Intent(getActivity(), AdvertLocationActivity.class);
Advert putadvert = DefaultApplication.dbc.getAdvertForAdvertID(Integer.parseInt(myMarker.get(arg0)));
myIntent.putExtra("advert", putadvert);
startActivity(myIntent);
}
});
return inflatedView;
}
private void setUpMapIfNeeded(View inflatedView) {
if (mMap == null) {
mMap = ((com.google.android.gms.maps.MapView) inflatedView.findViewById(R.id.map_tab)).getMap();
if (mMap != null) {
this.initMarker();
}
}
}
public void initMarker(){
for(int i=0;i<ads.size();i++){
Advert tempAd = ads.get(i);
LatLng tlalo = new LatLng(tempAd.mainLocation.latitude,tempAd.mainLocation.longitude);
builder.include(tlalo);
String address = "";
if(tempAd.mainLocation.contact_street != null){
address = address + tempAd.mainLocation.contact_street;
}
if(tempAd.mainLocation.contact_street_number != null){
address = address + " " + tempAd.mainLocation.contact_street_number;
}
Marker marker = mMap.addMarker(new MarkerOptions()
.position(tlalo)
.anchor(0.5f, 0.5f)
.title(tempAd.name)
.snippet(address)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.androidpin)));
myMarker.put(marker,String.valueOf(tempAd.myid));
}
mMap.setOnCameraChangeListener(new OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition arg0) {
mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 100));
mMap.setOnCameraChangeListener(null);
}
});
}
#Override
public void onResume() {
super.onResume();
m.onResume();
}
#Override
public void onPause() {
super.onPause();
m.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
m.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
m.onLowMemory();
}
}
try add this in onCreateView()
container.removeAllViews();
I found it in another similar question to yours but I lost the original link of the answer...