dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.google.android.support:wearable:1.2.0' compile 'com.google.android.gms:play-services:7.5.0'}
dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) wearApp project(':wear') compile 'com.google.android.gms:play-services:7.5.0' compile 'com.android.support:appcompat-v7:22.1.1' compile 'com.firebase:firebase-client-android:2.3.0+'}
// Setup onclick event listener for the mapmMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() { @Override public void onMapClick(LatLng point) { // Logic to add markers to the map on click. … LatLng origin = (LatLng) bikeMarkerList.get(0).getPosition(); LatLng dest = (LatLng) bikeMarkerList.get(1).getPosition(); // Get URLs for the Directions API String url = getDirectionsUrl(origin, dest); // Create an AsyncTask to fetch JSON data from Directions API DirectionsDownloadTask downloadTask = new DirectionsDownloadTask(); downloadTask.execute(url); }});
// Building the url to the Directions API web serviceprivate String getDirectionsUrl(LatLng origin,LatLng dest){// String for the origin of the routeString str_origin = "origin="+origin.latitude+","+origin.longitude;// String for the destination of the routeString str_dest = "destination="+dest.latitude+","+dest.longitude;// Enable bicycling modeString mode = "mode=bicycling";// We build the parameters for our URL stringString parameters = str_origin+"&"+str_dest+"&"+mode;// Construction of the entire URL to the Directions API. // IMPORTANT: Notice how we proxy the requests through a web server to// protect your API key.String url = "https://<YOUR_PROXY_SERVER>/directions?"+parameters;return url;}
protected void onPostExecute(String directionsJSON) { super.onPostExecute(directionsJSON); try { JSONObject jObject = new JSONObject(directionsJSON); DirectionsJSONParser parser = new DirectionsJSONParser(); // Parse the data. directionsResult is a List of decoded poly directionsResult = parser.parse(jObject); // This is the encoded polyline to pass on the Elevation API call String overviewPolyline = parser.getEncodedPoly(jObject); //Now that we have route, we need to get the Elevation data. ElevationDownloadTask elevationDownloadTask = new ElevationDownloadTask(); String url = getElevationUrl(overviewPolyline); elevationDownloadTask.execute(url); } catch (Exception ex) { ex.printStackTrace(); }}
private String getElevationUrl(String encodedPolyline) { // Build parameters to the web service String parameters = "locations=enc:" + encodedPolyline; // Build URL to the web service String url = "https://<YOUR_PROXY_SERVER>/elevation?" + parameters; return url;}
protected void onPostExecute(String elevationJSON) { super.onPostExecute(elevationJSON); try { JSONObject jObject = new JSONObject(elevationJSON); ElevationJSONParser parser = new ElevationJSONParser(); // Start parsing data elevationResult = parser.parse(jObject); // We use later send this to the Wearable device to recreate poly. String routeForWearable = ""; // Go through all segments for (int i = 1; i < directionsResult.size(); i++) { LatLng prevPosition = directionsResult.get(i - 1); LatLng position = directionsResult.get(i); double prevElevation = Double.valueOf(elevationResult.get(i - 1)); double elevation = Double.valueOf(elevationResult.get(i)); double elevationDiff = elevation - prevElevation; // Get color based on elevation change. // Green --> Red (and vice versa) gradient logic. int color = getColorByElevChange(elevationDiff); // Create the polyline segment. PolylineOptions polyOptions = new PolylineOptions() .add(prevPosition, position) .color(color) .width(8); // Draw polyline for segment mMap.addPolyline(polyOptions); // We maintain this String variable to pass over via the DataApi to the Wearable // app. From there we parse the response and also create the polyline there. routeForWearable += prevPosition.latitude + "," + prevPosition.longitude + ":" + position.latitude + "," + position.longitude + ":" + color + "|"; } // Here we send over the polyline string to the Wearable device. PutDataMapRequest putDataMapReq = PutDataMapRequest.create("/route"); putDataMapReq.getDataMap().putString(ROUTE_TAG, routeForWearable); PutDataRequest putDataReq = putDataMapReq.asPutDataRequest(); PendingResult pendingResult = Wearable.DataApi.putDataItem(mGoogleApiClient, putDataReq); } catch (Exception e) { e.printStackTrace(); }}
public void onDataChanged(DataEventBuffer dataEvents) {… // Initialization logicfor (DataEvent event : dataEvents) { if (event.getType() == DataEvent.TYPE_CHANGED) { // DataItem changed DataItem item = event.getDataItem(); if (item.getUri().getPath().compareTo("/route") == 0) { DataMap dataMap = DataMapItem.fromDataItem(item).getDataMap(); String routeFromMobile = dataMap.getString(ROUTE_TAG); // Go back to main UI thread and draw polyline // Broadcast message to wearable activity for display Intent messageIntent = new Intent(); messageIntent.setAction(Intent.ACTION_SEND); messageIntent.putExtra(ROUTE_TAG, routeFromMobile); LocalBroadcastManager.getInstance(this).sendBroadcast(messageIntent); } } else if (event.getType() == DataEvent.TYPE_DELETED) { // DataItem deleted }}}
public class MessageReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String routeFromMobile = intent.getStringExtra(ROUTE_TAG); // Draw the elevation polyline based on parsing the String. drawElevationPolyline(routeFromMobile); }}
@Overridepublic boolean onOptionsItemSelected(MenuItem item) { // Handle presses on the action bar items switch (item.getItemId()) { case R.id.action_search: try { PlacePicker.IntentBuilder intentBuilder = new PlacePicker.IntentBuilder(); Intent intent = intentBuilder.build(this); // Start the Intent by requesting a result, identified by a request code. startActivityForResult(intent, REQUEST_PLACE_PICKER); } catch (GooglePlayServicesRepairableException e) { GooglePlayServicesUtil.getErrorDialog(e.getConnectionStatusCode(), this, 0); } catch (GooglePlayServicesNotAvailableException e) { Toast.makeText(this, "Google Play Services is not available.",Toast.LENGTH_LONG).show(); } return true; default: return super.onOptionsItemSelected(item); }}
final Place place = PlacePicker.getPlace(data, this);
final CharSequence name = place.getName();final CharSequence address = place.getAddress();final CharSequence phone = place.getPhoneNumber();
mMap.addMarker(new MarkerOptions() .position(place.getLatLng()) .title(name.toString())
@Overridepublic void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_PLACE_PICKER) { // This result is from the PlacePicker dialog. if (resultCode == Activity.RESULT_OK) { /* User has picked a place, extract data. Data is extracted from the returned intent by retrieving a Place object from the PlacePicker. */ final Place place = PlacePicker.getPlace(data, this); /* A Place object contains details about that place, such as its name, address and phone number. Extract the name, address, phone number, place ID and place types. */ final CharSequence name = place.getName(); final CharSequence address = place.getAddress(); final CharSequence phone = place.getPhoneNumber(); final String placeId = place.getId(); String attribution = PlacePicker.getAttributions(data); if(attribution == null){ attribution = ""; } // Update data on map mMap.addMarker(new MarkerOptions() .position(place.getLatLng()) .title(name.toString()) ); // Print data to debug log Log.d(TAG, "Place selected: " + placeId + " (" + name.toString() + ")"); } } else { super.onActivityResult(requestCode, resultCode, data); } // END_INCLUDE(activity_result)}
Map mLocation = new HashMap();mLocation.put("timestamp", mLastUpdateTime);Map mCoordinate = new HashMap();mCoordinate.put(“latitude”, place.getLatLng().latitude);mCoordinate.put(“longitude”, place.getLatLng().longitude);mLocation.put("location", mCoordinate); mLocation.put("place_id", place.getId());myFirebaseRef.push().setValue(mLocation);
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
public class MapsActivity extends FragmentActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {}
protected synchronized void buildGoogleApiClient() { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build();}
@Overridepublic void onConnected(Bundle bundle) { mLastLocation = LocationServices.FusedLocationApi.getLastLocation( mGoogleApiClient); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom( new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude()), MAP_ZOOM_LEVEL));}
public static final long UPDATE_INTERVAL_IN_MS = 120000; public static final long FASTEST_UPDATE_INTERVAL_IN_MS =UPDATE_INTERVAL_IN_MS / 4;protected LocationRequest mLocationRequest;
private void startLogging() { mLocationRequest = new LocationRequest(); mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MS); mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MS); mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); if (mGoogleApiClient.isConnected() && !mRequestingLocationUpdates) { mRequestingLocationUpdates = true; startLocationUpdates(); }} protected void startLocationUpdates() { LocationServices.FusedLocationApi.requestLocationUpdates( mGoogleApiClient, mLocationRequest, this);}
@Overridepublic void onLocationChanged(Location location) { mCurrentLocation = location; DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); Date date = new Date(); mLastUpdateTime = dateFormat.format(date).toString(); saveToFirebase(); // Retrieve saved locations and draw as marker on map drawLocations(); // Update UI to draw bread crumb with the latest bus location. mMap.clear(); LatLng mLatlng = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude()); MarkerOptions mMarkerOption = new MarkerOptions() .position(mLatlng) .title(mLastUpdateTime)) .icon(BitmapDescriptorFactory.fromResource(R.drawable.code_the_road_small)); Marker mMarker = mMap.addMarker(mMarkerOption); }
myFirebaseRef = new Firebase("<YOUR-FIREBASE-APP>");
private void saveToFirebase() { Map mLocations = new HashMap(); mLocations.put("timestamp", mLastUpdateTime); Map mCoordinate = new HashMap(); mCoordinate.put(“latitude”, mCurrentLocation.getLatitude()); mCoordinate.put(“longitude”, mCurrentLocation.getLongitude()); mLocations.put("location", mCoordinate); myFirebaseRef.push().setValue(mLocations);}
private void drawLocations() { // Get only latest logged locations - since 'START' button clicked Query queryRef = myFirebaseRef.orderByChild("timestamp").startAt(startLoggingTime); // Add listener for a child added at the data at this location queryRef.addChildEventListener(new ChildEventListener() { LatLngBounds bounds; LatLngBounds.Builder builder = new LatLngBounds.Builder(); @Override public void onChildAdded(DataSnapshot dataSnapshot, String s) { Map data = (Map ) dataSnapshot.getValue(); String timestamp = (String) data.get("timestamp"); // Get recorded latitude and longitude Map mCoordinate = (HashMap)data.get("location"); double latitude = (double) (mCoordinate.get("latitude")); double longitude = (double) (mCoordinate.get("longitude")); // Create LatLng for each locations LatLng mLatlng = new LatLng(latitude, longitude); // Make sure the map boundary contains the location builder.include(mLatlng); bounds = builder.build(); // Add a marker for each logged location MarkerOptions mMarkerOption = new MarkerOptions() .position(mLatlng) .title(timestamp) .icon(BitmapDescriptorFactory.fromResource(R.drawable.measle_blue)); Marker mMarker = mMap.addMarker(mMarkerOption); markerList.add(mMarker); // Zoom map to the boundary that contains every logged location mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, MAP_ZOOM_LEVEL)); } //Override other abstract methods for addChildEventListener below … }); }
Give us feedback in our Product Forums.