CS5530 Mobile/Wireless Systems Using Google Map in Android Yanyan - - PowerPoint PPT Presentation

cs5530 mobile wireless systems using google map in android
SMART_READER_LITE
LIVE PREVIEW

CS5530 Mobile/Wireless Systems Using Google Map in Android Yanyan - - PowerPoint PPT Presentation

CS5530 Mobile/Wireless Systems Using Google Map in Android Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang UC. Colorado Springs CS5530 Ref. CN5E, NT@UW, WUSTL Setup Install the Google Play services SDK o


slide-1
SLIDE 1
  • Ref. CN5E, NT@UW, WUSTL

CS5530

CS5530 Mobile/Wireless Systems Using Google Map in Android

Yanyan Zhuang

Department of Computer Science http://www.cs.uccs.edu/~yzhuang

  • UC. Colorado Springs
slide-2
SLIDE 2

Setup

  • Ref. CN5E, NT@UW, WUSTL

2 CS5530

  • Install the Google Play services SDK
  • Tools > Android > SDK manager
slide-3
SLIDE 3

Create a Google Maps project

  • Ref. CN5E, NT@UW, WUSTL

3 CS5530

  • Select Google Maps Activity in the 'Add an activity to

Mobile' dialog

  • When build finished, Android Studio opens

google_maps_api.xml and MapsActivity.java

  • google_maps_api.xml contains instructions on getting a Google Maps

API key before you try to run the application.

slide-4
SLIDE 4

Get a Google Maps API key

  • Ref. CN5E, NT@UW, WUSTL

4 CS5530

  • Apps need an API key to access Google Maps servers
  • The key is free. You can use it with any of your applications that call the Google Maps

Android API, and it supports an unlimited number of users

1. Copy the link in google_maps_api.xml, paste it into browser 2. Follow the instructions to create a new project on the Google API Console or select an existing project 3. Create an Android-restricted API key for your project 4. Copy the resulting API key, go back to Android Studio, and paste the API key into the <string> element in google_maps_api.xml May use the same key for more than one app

slide-5
SLIDE 5

Run the app

  • Ref. CN5E, NT@UW, WUSTL

5 CS5530

  • By default, the XML file that defines the app's layout

is at res/layout/activity_maps.xml

  • The simplest way to see your app in action is to

connect an Android device to your computer

  • You can use Android Emulator to run app
  • When choosing an emulator, use Android 4.2.2 or higher, and be careful

to pick an image that includes the Google APIs, or the application will not have the runtime APIs in order to execute

slide-6
SLIDE 6

Run the app (2)

  • Ref. CN5E, NT@UW, WUSTL

6 CS5530

  • You should see a map with a marker positioned over

Sydney, Australia

  • If you don't see a map, check that you've added an API key as described
  • Check the log in Android Studio's Android Monitor for error messages

about the API key

  • Different ways to get the API key

https://developers.google.com/maps/documentation/android- api/signup

slide-7
SLIDE 7

Understand the code

  • Ref. CN5E, NT@UW, WUSTL

7 CS5530

  • AndroidManifest.xml
  • <meta-data

android:name="com.google.android.geo.API_KEY" android:value="@string/google_maps_key" /> (generated for you)

  • activity_maps.xml
  • <fragment> element to your activity's layout file
  • Defines a SupportMapFragment to act as a container for the map and to

provide access to the GoogleMap object

<fragment name="com.google.android.gms.maps.SupportMapFragment" android:layout_width="match_parent" android:layout_height="match_parent"/>

slide-8
SLIDE 8

Understand the code

  • Ref. CN5E, NT@UW, WUSTL

8 CS5530

  • What is a fragment?
  • A Fragment represents a behavior or a portion of user interface in

an Activity

  • Can combine multiple fragments in a single activity to build a multi-pane

UI and reuse a fragment in multiple activities

  • Can think of a fragment as a modular section of an activity, which has its
  • wn lifecycle, receives its own input events, and which you can add or

remove while the activity is running

} sort of like a "sub activity" that you can reuse in different activities

slide-9
SLIDE 9

Understand the code

  • Ref. CN5E, NT@UW, WUSTL

9 CS5530

  • MapsActivity’s onCreate()
  • @Override

protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // set the layout file as the content view setContentView(R.layout.activity_maps); // get a handle to the map fragment SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); // use getMapAsync() to register for map callback (when map is ready) mapFragment.getMapAsync(this); }

slide-10
SLIDE 10

Understand the code

  • Ref. CN5E, NT@UW, WUSTL

10 CS5530

  • Implement OnMapReadyCallback interface & override
  • nMapReady(): set up the map when GoogleMap object is

available

  • public class MapsActivity extends AppCompatActivity

implements OnMapReadyCallback { // OnCreate() method here: as described on last slide @Override public void onMapReady(GoogleMap googleMap) { // Add a marker in Sydney, Australia, and move map's camera LatLng sydney = new LatLng(-33.852, 151.211); googleMap.addMarker(new MarkerOptions().position(sydney) .title("Marker in Sydney")); googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney)); } }

slide-11
SLIDE 11

Understand the code

  • Ref. CN5E, NT@UW, WUSTL

11 CS5530

  • By default, the Google Maps API displays the content
  • f “title” when the user taps a marker
  • googleMap.addMarker(new MarkerOptions().position(sydney)

.title("Marker in Sydney"));

  • There's no need to add a click listener for the marker

if you’re happy with the default behavior

slide-12
SLIDE 12

Summarize

  • Ref. CN5E, NT@UW, WUSTL

12 CS5530

  • The basic steps for adding a map

1.

(You only need to do this once) Get Google Play Service SDK, obtain a key and add the required attributes to Android manifest

2.

Add a <fragment> element to the layout file for the Activity

3.

Call getMapAsync() on the fragment to register the callback

4.

Implement the OnMapReadyCallback interface and use the onMapReady(GoogleMap) callback to get a handle to the GoogleMap object

slide-13
SLIDE 13

Map Types

  • Ref. CN5E, NT@UW, WUSTL

13 CS5530

  • Normal
  • Hybrid
  • Terrain
  • Satellite
  • None
  • GoogleMap map;

... // Sets the map type to be "hybrid" map.setMapType(GoogleMap.MAP_TYPE_HYBRID);

slide-14
SLIDE 14

Markers

  • Ref. CN5E, NT@UW, WUSTL

14 CS5530

  • You can customize markers by changing the default

color, or replacing the marker icon with a custom image

  • Info windows can provide additional context to a marker
  • Markers are objects of type Marker
  • Added to map with the GoogleMap.addMarker(markerOptions) method
  • Receive click events by default, and are often used with event listeners

to bring up info windows

  • Previous example

} googleMap.addMarker(new MarkerOptions().position(sydney).title("Marker in

Sydney"));

slide-15
SLIDE 15

Markers

  • Ref. CN5E, NT@UW, WUSTL

15 CS5530

  • Some other examples
  • Marker marker = googleMap.addMarker(new

MarkerOptions().position(new LatLng(-34, 151)));

  • marker.revmote();
  • Setting a marker to be invisible, and transparency

Marker marker = googleMap.addMarker(new MarkerOptions().position(new LatLng(-34, 151)).visible(false).alpha(0.8f));

slide-16
SLIDE 16

Markers

  • Ref. CN5E, NT@UW, WUSTL

16 CS5530

  • Once a marker is created, you can change its property
  • marker.setAlpha(1.0f);
  • marker.setVisible(true);
  • marker.setPosition(new LatLng(-34, 151));
  • Why marker visibility?
  • Faster to make an invisible marker visible, than creating a new marker
  • Show information
  • googleMap.addMarker(new

MarkerOptions().position(sydney).title("Sydney").snippet(“Population: 4.5 million in 2015”));

slide-17
SLIDE 17

Markers

  • Ref. CN5E, NT@UW, WUSTL

17 CS5530

  • Respond to click events
  • Activity must implement GoogleMap.OnMarkerClickListener
  • Set a listener for marker click

} @Override

public void onMapReady(GoogleMap googleMap) { …... mMap.setOnMarkerClickListener(this); }

  • Implement callback function onMarkerClick()
slide-18
SLIDE 18

Markers

  • Ref. CN5E, NT@UW, WUSTL

18 CS5530

  • Respond to click events
  • Implement callback function onMarkerClick()

} @Override

public boolean onMarkerClick(final Marker marker) { if (marker.equals(myMarker)) { Toast.makeText(this, marker.getTitle() + " has been clicked!", Toast.LENGTH_LONG).show(); } return false; }

slide-19
SLIDE 19

Toasts

  • Ref. CN5E, NT@UW, WUSTL

19 CS5530

  • A toast provides simple feedback about an operation

in a small pop-up

  • Only fills the amount of space required for the message and the current

activity remains visible and interactive

  • Toasts automatically disappear after a timeout
  • Instantiate a Toast object with makeText() method
  • 3 parameters: the application Context (usually this), the text message,

and the duration for the toast

  • Toast.LENGTH_SHORT and Toast.LENGTH_LONG
slide-20
SLIDE 20

Toasts

  • Ref. CN5E, NT@UW, WUSTL

20 CS5530

  • Example
  • Context context = getApplicationContext();

CharSequence text = "Hello toast!"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show();

  • Toast.makeText(context, text, duration).show();
slide-21
SLIDE 21

Toasts

  • Ref. CN5E, NT@UW, WUSTL

21 CS5530

  • Positioning your Toast
  • A standard toast notification appears near the bottom of the screen,

centered horizontally

  • You can change this position with the setGravity(int, int, int) method:

a Gravity constant, an x-position offset, and a y-position offset

  • If the toast should appear in the top-left corner

} toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0); } If you want to nudge the position to the right, increase the value of the second

  • parameter. To nudge it down, increase the value of the last parameter
slide-22
SLIDE 22

Select Current Place

  • Ref. CN5E, NT@UW, WUSTL

22 CS5530

  • Create a Google API client
  • Also known as the Google API client: connect with fused location

provider and Google Places API

} private GoogleApiClient mGoogleApiClient;

slide-23
SLIDE 23

Select Current Place

  • Ref. CN5E, NT@UW, WUSTL

23 CS5530

  • Build a Google API client
  • Request the fused location provider (LocationServices.API) and the two

parts of the Google Places API for Android (Places.GEO_DATA_API and Places.PLACE_DETECTION_API)

  • mGoogleApiClient = new GoogleApiClient.Builder(this)

.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */) .addConnectionCallbacks(this) .addApi(LocationServices.API) .addApi(Places.GEO_DATA_API) .addApi(Places.PLACE_DETECTION_API) .build(); mGoogleApiClient.connect();

slide-24
SLIDE 24

Select Current Place

  • Ref. CN5E, NT@UW, WUSTL

24 CS5530

  • Cannot resolve LocationServices and Places
  • Add dependencies in build.gradle (Module: app)
  • compile 'com.google.android.gms:play-services-location:10.2.0'

compile 'com.google.android.gms:play-services-places:10.2.0’

  • Sync
  • Then we can import classes for LocationServices and Places
slide-25
SLIDE 25

Select Current Place

  • Ref. CN5E, NT@UW, WUSTL

25 CS5530

  • Call back functions of mGoogleApiClient.connect()
  • @Override

public void onConnected(Bundle connectionHint) { ... } /* Handles failure to connect to the Google Play services client. */ @Override public void onConnectionFailed(@NonNull ConnectionResult result) { Log.d(TAG, "Play services connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode()); } /* Handles suspension of the connection to the Google Play services client. */ @Override public void onConnectionSuspended(int cause) { Log.d(TAG, "Play services connection suspended"); }

slide-26
SLIDE 26

Location Services API

  • Ref. CN5E, NT@UW, WUSTL

26 CS5530

  • Enables or disables the my-location layer
  • mMap.setMyLocationEnabled(true);
  • While enabled and the location is available, the my-location layer

continuously draws an indication of a user's current location and bearing, and displays UI controls that allow a user to interact with their location

  • In order to use the my-location-layer feature you need to request

permission for either ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION

slide-27
SLIDE 27

Location Services API

  • Ref. CN5E, NT@UW, WUSTL

27 CS5530

  • Enables or disables the my-location button
  • mMap.getUiSettings().setMyLocationButtonEnabled(true)
  • The my-location button causes the camera to move such that the user's

location is in the center of the map. If the button is enabled, it is only shown when the my-location layer is enabled

  • By default, the my-location button is enabled
slide-28
SLIDE 28

Location Services API

  • Ref. CN5E, NT@UW, WUSTL

28 CS5530

  • Get the best and most recent location of the device

(may be null in cases when a location is not available)

  • mLastKnownLocation = LocationServices.FusedLocationApi

.getLastLocation(mGoogleApiClient);

  • Set the map's camera position to the current location
  • f the device and zoom in
  • if (mLastKnownLocation != null) {

mMap.moveCamera(CameraUpdateFactory.newLatLngZoom( new LatLng(mLastKnownLocation.getLatitude(), mLastKnownLocation.getLongitude()), DEFAULT_ZOOM)); }

slide-29
SLIDE 29

Place Detection API

  • Ref. CN5E, NT@UW, WUSTL

29 CS5530

  • Get an estimate of the place where the device is

currently located

  • PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi

.getCurrentPlace(mGoogleApiClient, null);

  • Generates a PlaceLikelihoodBuffer based on device's last estimated

location

  • Returned values may be obtained by means of a network lookup: results

are a best guess and not guaranteed to be correct

  • Requires ACCESS_FINE_LOCATION permission
  • Access to this method is subject to quota restrictions
slide-30
SLIDE 30

Place Detection API

  • Ref. CN5E, NT@UW, WUSTL

30 CS5530

  • Populate place information
  • result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {

@Override public void onResult(@NonNull PlaceLikelihoodBuffer likelyPlaces) { mLikelyPlaceNames = new String[mMaxEntries]; … for (PlaceLikelihood placeLikelihood : likelyPlaces) { // Build a list of likely places to show the user. Max 5. mLikelyPlaceNames[i] = (String) placeLikelihood.getPlace().getName(); … } // Release the place likelihood buffer, to avoid memory leaks. likelyPlaces.release(); } });

slide-31
SLIDE 31

Setting an AlertDialog for Users to Pick

  • Ref. CN5E, NT@UW, WUSTL

31 CS5530

  • AlertDialog lets users to interact with the app
  • AlertDialog dialog = new AlertDialog.Builder(this)

.setTitle("pick a place") .setItems(mLikelyPlaceNames, listener) .show();

  • Syntax: use AlertDialog.Builder’s method setItems (CharSequence[]

items, DialogInterface.OnClickListener listener)

} Set a list of items to be displayed in the dialog as the content } Code will be notified of the selected item via the supplied listener } Implement the listener

slide-32
SLIDE 32

Setting an AlertDialog for Users to Pick

  • Ref. CN5E, NT@UW, WUSTL

32 CS5530

  • Listener
  • DialogInterface.OnClickListener listener =

new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // The "which" argument contains the position of the selected item. LatLng markerLatLng = mLikelyPlaceLatLngs[which]; String markerSnippet = mLikelyPlaceAddresses[which]; ... // Add a marker for the selected place, with an info window w/ information about that place mMap.addMarker(new MarkerOptions() .title(mLikelyPlaceNames[which]) .position(markerLatLng) .snippet(markerSnippet)); // Position the map's camera at the location of the marker. mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(markerLatLng, DEFAULT_ZOOM)); } };