-
Notifications
You must be signed in to change notification settings - Fork 3k
/
MarkerDemoActivity.java
509 lines (428 loc) · 18.5 KB
/
MarkerDemoActivity.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
// Copyright 2020 Google LLC
//
// 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.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowCloseListener;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowLongClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerDragListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import androidx.annotation.ColorInt;
import androidx.annotation.DrawableRes;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.res.ResourcesCompat;
import androidx.core.graphics.drawable.DrawableCompat;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.animation.BounceInterpolator;
import android.view.animation.Interpolator;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* This shows how to place markers on a map.
*/
// [START maps_android_sample_marker]
public class MarkerDemoActivity extends AppCompatActivity implements
OnMarkerClickListener,
OnInfoWindowClickListener,
OnMarkerDragListener,
OnSeekBarChangeListener,
OnInfoWindowLongClickListener,
OnInfoWindowCloseListener,
OnMapAndViewReadyListener.OnGlobalLayoutAndMapReadyListener {
private static final LatLng BRISBANE = new LatLng(-27.47093, 153.0235);
private static final LatLng MELBOURNE = new LatLng(-37.81319, 144.96298);
private static final LatLng DARWIN = new LatLng(-12.4634, 130.8456);
private static final LatLng SYDNEY = new LatLng(-33.87365, 151.20689);
private static final LatLng ADELAIDE = new LatLng(-34.92873, 138.59995);
private static final LatLng PERTH = new LatLng(-31.952854, 115.857342);
private static final LatLng ALICE_SPRINGS = new LatLng(-24.6980, 133.8807);
/** Demonstrates customizing the info window and/or its contents. */
class CustomInfoWindowAdapter implements InfoWindowAdapter {
// These are 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);
}
@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;
// Use the equals() method on a Marker to check for equals. Do not use ==.
if (marker.equals(mBrisbane)) {
badge = R.drawable.badge_qld;
} else if (marker.equals(mAdelaide)) {
badge = R.drawable.badge_sa;
} else if (marker.equals(mSydney)) {
badge = R.drawable.badge_nsw;
} else if (marker.equals(mMelbourne)) {
badge = R.drawable.badge_victoria;
} else if (marker.equals(mPerth)) {
badge = R.drawable.badge_wa;
} else if (marker.equals(mDarwin1)) {
badge = R.drawable.badge_nt;
} else if (marker.equals(mDarwin2)) {
badge = R.drawable.badge_nt;
} else if (marker.equals(mDarwin3)) {
badge = R.drawable.badge_nt;
} else if (marker.equals(mDarwin4)) {
badge = R.drawable.badge_nt;
} else {
// Passing 0 to setImageResource will clear the image view.
badge = 0;
}
((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 mPerth;
private Marker mSydney;
private Marker mBrisbane;
private Marker mAdelaide;
private Marker mMelbourne;
private Marker mDarwin1;
private Marker mDarwin2;
private Marker mDarwin3;
private Marker mDarwin4;
/**
* Keeps track of the last selected marker (though it may no longer be selected). This is
* useful for refreshing the info window.
*/
private Marker mLastSelectedMarker;
private final List<Marker> mMarkerRainbow = new ArrayList<Marker>();
private TextView mTopText;
private SeekBar mRotationBar;
private CheckBox mFlatBox;
private RadioGroup mOptions;
private final Random mRandom = new Random();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.marker_demo);
mTopText = (TextView) findViewById(R.id.top_text);
mRotationBar = (SeekBar) findViewById(R.id.rotationSeekBar);
mRotationBar.setMax(360);
mRotationBar.setOnSeekBarChangeListener(this);
mFlatBox = (CheckBox) findViewById(R.id.flat);
mOptions = (RadioGroup) findViewById(R.id.custom_info_window_options);
mOptions.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (mLastSelectedMarker != null && mLastSelectedMarker.isInfoWindowShown()) {
// Refresh the info window when the info window's content has changed.
mLastSelectedMarker.showInfoWindow();
}
}
});
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
new OnMapAndViewReadyListener(mapFragment, this);
}
@Override
public void onMapReady(GoogleMap map) {
mMap = map;
// 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);
mMap.setOnInfoWindowCloseListener(this);
mMap.setOnInfoWindowLongClickListener(this);
// Override the default content description on the view, for accessibility mode.
// Ideally this string would be localised.
mMap.setContentDescription("Map with lots of markers.");
LatLngBounds bounds = new LatLngBounds.Builder()
.include(PERTH)
.include(SYDNEY)
.include(ADELAIDE)
.include(BRISBANE)
.include(MELBOURNE)
.include(DARWIN)
.build();
mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 50));
}
private void addMarkersToMap() {
// Uses a colored icon.
mBrisbane = mMap.addMarker(new MarkerOptions()
.position(BRISBANE)
.title("Brisbane")
.snippet("Population: 2,074,200")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
// Uses a custom icon with the info window popping out of the center of the icon.
mSydney = mMap.addMarker(new MarkerOptions()
.position(SYDNEY)
.title("Sydney")
.snippet("Population: 4,627,300")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.arrow))
.infoWindowAnchor(0.5f, 0.5f));
// Creates a draggable marker. Long press to drag.
mMelbourne = mMap.addMarker(new MarkerOptions()
.position(MELBOURNE)
.title("Melbourne")
.snippet("Population: 4,137,400")
.draggable(true));
// Place four markers on top of each other with differing z-indexes.
mDarwin1 = mMap.addMarker(new MarkerOptions()
.position(DARWIN)
.title("Darwin Marker 1")
.snippet("z-index 1")
.zIndex(1));
mDarwin2 = mMap.addMarker(new MarkerOptions()
.position(DARWIN)
.title("Darwin Marker 2")
.snippet("z-index 2")
.zIndex(2));
mDarwin3 = mMap.addMarker(new MarkerOptions()
.position(DARWIN)
.title("Darwin Marker 3")
.snippet("z-index 3")
.zIndex(3));
mDarwin4 = mMap.addMarker(new MarkerOptions()
.position(DARWIN)
.title("Darwin Marker 4")
.snippet("z-index 4")
.zIndex(4));
// A few more markers for good measure.
mPerth = mMap.addMarker(new MarkerOptions()
.position(PERTH)
.title("Perth")
.snippet("Population: 1,738,800"));
mAdelaide = mMap.addMarker(new MarkerOptions()
.position(ADELAIDE)
.title("Adelaide")
.snippet("Population: 1,213,000"));
// Vector drawable resource as a marker icon.
mMap.addMarker(new MarkerOptions()
.position(ALICE_SPRINGS)
.icon(vectorToBitmap(R.drawable.ic_android, Color.parseColor("#A4C639")))
.title("Alice Springs"));
// Creates a marker rainbow demonstrating how to create default marker icons of different
// hues (colors).
float rotation = mRotationBar.getProgress();
boolean flat = mFlatBox.isChecked();
int numMarkersInRainbow = 12;
for (int i = 0; i < numMarkersInRainbow; i++) {
Marker marker = mMap.addMarker(new MarkerOptions()
.position(new LatLng(
-30 + 10 * Math.sin(i * Math.PI / (numMarkersInRainbow - 1)),
135 - 10 * Math.cos(i * Math.PI / (numMarkersInRainbow - 1))))
.title("Marker " + i)
.icon(BitmapDescriptorFactory.defaultMarker(i * 360 / numMarkersInRainbow))
.flat(flat)
.rotation(rotation));
mMarkerRainbow.add(marker);
}
}
/**
* Demonstrates converting a {@link Drawable} to a {@link BitmapDescriptor},
* for use as a marker icon.
*/
private BitmapDescriptor vectorToBitmap(@DrawableRes int id, @ColorInt int color) {
Drawable vectorDrawable = ResourcesCompat.getDrawable(getResources(), id, null);
Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(),
vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
DrawableCompat.setTint(vectorDrawable, color);
vectorDrawable.draw(canvas);
return BitmapDescriptorFactory.fromBitmap(bitmap);
}
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();
}
/** Called when the Reset button is clicked. */
public void onToggleFlat(View view) {
if (!checkReady()) {
return;
}
boolean flat = mFlatBox.isChecked();
for (Marker marker : mMarkerRainbow) {
marker.setFlat(flat);
}
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (!checkReady()) {
return;
}
float rotation = seekBar.getProgress();
for (Marker marker : mMarkerRainbow) {
marker.setRotation(rotation);
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// Do nothing.
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// Do nothing.
}
//
// Marker related listeners.
//
@Override
public boolean onMarkerClick(final Marker marker) {
if (marker.equals(mPerth)) {
// This causes the marker at Perth to bounce into position when it is clicked.
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final long duration = 1500;
final Interpolator interpolator = new BounceInterpolator();
handler.post(new Runnable() {
@Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start;
float t = Math.max(
1 - interpolator.getInterpolation((float) elapsed / duration), 0);
marker.setAnchor(0.5f, 1.0f + 2 * t);
if (t > 0.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
}
}
});
} else if (marker.equals(mAdelaide)) {
// This causes the marker at Adelaide to change color and alpha.
marker.setIcon(BitmapDescriptorFactory.defaultMarker(mRandom.nextFloat() * 360));
marker.setAlpha(mRandom.nextFloat());
}
// Markers have a z-index that is settable and gettable.
float zIndex = marker.getZIndex() + 1.0f;
marker.setZIndex(zIndex);
Toast.makeText(this, marker.getTitle() + " z-index set to " + zIndex,
Toast.LENGTH_SHORT).show();
mLastSelectedMarker = marker;
// 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(this, "Click Info Window", Toast.LENGTH_SHORT).show();
}
@Override
public void onInfoWindowClose(Marker marker) {
//Toast.makeText(this, "Close Info Window", Toast.LENGTH_SHORT).show();
}
@Override
public void onInfoWindowLongClick(Marker marker) {
Toast.makeText(this, "Info Window long click", 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());
}
}
// [END maps_android_sample_marker]