I'm not able to see the Map on my Activity.
I get this error on the console when running the app.
Things that I've done: API is Enabled for Google Maps Get the SHA1 fingerprint from debug.keystore Added the SHA1 fingerprint with package name Put the API Key in the manifest
What is the problem according to you? Help me please!
07-03 01:54:50.278: D/dalvikvm(374): GC_CONCURRENT freed 376K, 48% free 3040K/5831K, external 716K/1038K, paused 3ms+2ms 07-03 01:54:50.588: D/dalvikvm(374): GC_CONCURRENT freed 576K, 50% free 3021K/6023K, external 716K/1038K, paused 2ms+3ms 07-03 01:54:50.748: D/dalvikvm(374): GC_CONCURRENT freed 309K, 47% free 3218K/6023K, external 723K/1038K, paused 2ms+3ms 07-03 01:54:50.878: I/MapActivity(374): Handling network change notification:CONNECTED 07-03 01:54:50.878: E/MapActivity(374): Couldn't get connection factory client 07-03 01:54:50.968: D/dalvikvm(374): GC_EXTERNAL_ALLOC freed 228K, 50% free 3055K/6023K, external 871K/1038K, paused 51ms 07-03 01:54:51.558: W/System.err(374): IOException processing: 26 07-03 01:54:51.558: W/System.err(374): java.io.IOException: Server returned: 3 07-03 01:54:51.558: W/System.err(374): at android_maps_conflict_avoidance.com.google.googlenav.map.BaseTileRequest.readResponseData(BaseTileRequest.java:115) 07-03 01:54:51.558: W/System.err(374): at android_maps_conflict_avoidance.com.google.googlenav.map.MapService$MapTileRequest.readResponseData(MapService.java:1473) 07-03 01:54:51.558: W/System.err(374): at android_maps_conflict_avoidance.com.google.googlenav.datarequest.DataRequestDispatcher.processDataRequest(DataRequestDispatcher.java:1117) 07-03 01:54:51.558: W/System.err(374): at android_maps_conflict_avoidance.com.google.googlenav.datarequest.DataRequestDispatcher.serviceRequests(DataRequestDispatcher.java:994) 07-03 01:54:51.558: W/System.err(374): at android_maps_conflict_avoidance.com.google.googlenav.datarequest.DataRequestDispatcher$DispatcherServer.run(DataRequestDispatcher.java:1702) 07-03 01:54:51.558: W/System.err(374): at java.lang.Thread.run(Thread.java:1019) 07-03 01:54:51.958: W/System.err(374): IOException processing: 26 07-03 01:54:51.968: W/System.err(374): java.io.IOException: Server returned: 3 07-03 01:54:51.968: W/System.err(374): at android_maps_conflict_avoidance.com.google.googlenav.map.BaseTileRequest.readResponseData(BaseTileRequest.java:115) 07-03 01:54:51.968: W/System.err(374): at android_maps_conflict_avoidance.com.google.googlenav.map.MapService$MapTileRequest.readResponseData(MapService.java:1473) 07-03 01:54:51.968: W/System.err(374): at android_maps_conflict_avoidance.com.google.googlenav.datarequest.DataRequestDispatcher.processDataRequest(DataRequestDispatcher.java:1117) 07-03 01:54:51.968: W/System.err(374): at android_maps_conflict_avoidance.com.google.googlenav.datarequest.DataRequestDispatcher.serviceRequests(DataRequestDispatcher.java:994) 07-03 01:54:51.968: W/System.err(374): at android_maps_conflict_avoidance.com.google.googlenav.datarequest.DataRequestDispatcher$DispatcherServer.run(DataRequestDispatcher.java:1702) 07-03 01:54:51.968: W/System.err(374): at java.lang.Thread.run(Thread.java:1019)
this is the code:
// RouteTracker.java
// Main MapActivity for the RouteTracker app.
package com.deitel.routetracker;
import android.app.AlertDialog;
import android.content.Context;
import android.location.Criteria;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.FrameLayout;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
public class RouteTracker extends MapActivity
{
private LocationManager locationManager; // gives location data
private MapView mapView; // displays a Google map
private MapController mapController; // manages map pan/zoom
private Location previousLocation; // previous reported location
private RouteOverlay routeOverlay; // Overlay that shows route on map
private long distanceTraveled; // total distance the user traveled
private BearingFrameLayout bearingFrameLayout; // rotates the MapView
private boolean tracking; // whether app is currently tracking
private long startTime; // time (in milliseconds) when tracking starts
private PowerManager.WakeLock wakeLock; // used to prevent device sleep
private boolean gpsFix; // whether we have a GPS fix for accurate data
private static final double MILLISECONDS_PER_HOUR = 1000 * 60 * 60;
private static final double MILES_PER_KILOMETER = 0.621371192;
private static final int MAP_ZOOM = 18; // Google Maps supports 1-21
// Called when the activity is first created
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// create new MapView using your Google Maps API key
bearingFrameLayout = new BearingFrameLayout(this,
getResources().getString(R.string.google_maps_api_key));
// add bearingFrameLayout to mainLayout
FrameLayout mainLayout =
(FrameLayout) findViewById(R.id.mainLayout);
mainLayout.addView(bearingFrameLayout, 0);
// get the MapView and MapController
mapView = bearingFrameLayout.getMapview();
mapController = mapView.getController(); // get MapController
mapController.setZoom(MAP_ZOOM); // zoom in the map
// create map Overlay
routeOverlay = new RouteOverlay();
// add the RouteOverlay overlay
mapView.getOverlays().add(routeOverlay);
distanceTraveled = 0; // initialize distanceTraveled to 0
// register listener for trackingToggleButton
ToggleButton trackingToggleButton =
(ToggleButton) findViewById(R.id.trackingToggleButton);
trackingToggleButton.setOnCheckedChangeListener(
trackingToggleButtonListener);
} // end onCreate
// called when Activity becoming visible to the user
@Override
public void onStart()
{
super.onStart(); // call super's onStart method
// create Criteria object to specify location provider's settings
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE); // fine location data
criteria.setBearingRequired(true); // need bearing to rotate map
criteria.setCostAllowed(true); // OK to incur monetary cost
criteria.setPowerRequirement(Criteria.POWER_LOW); // try to conserve
criteria.setAltitudeRequired(false); // don't need altitude data
// get the LocationManager
locationManager =
(LocationManager) getSystemService(LOCATION_SERVICE);
// register listener to determine whether we have a GPS fix
locationManager.addGpsStatusListener(gpsStatusListener);
// get the best provider based on our Criteria
String provider = locationManager.getBestProvider(criteria, true);
// listen for changes in location as often as possible
locationManager.requestLocationUpdates(provider, 0, 0,
locationListener);
// get the app's power manager
PowerManager powerManager =
(PowerManager) getSystemService(Context.POWER_SERVICE);
// get a wakelock preventing the device from sleeping
wakeLock = powerManager.newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK, "No sleep");
wakeLock.acquire(); // acquire the wake lock
bearingFrameLayout.invalidate(); // redraw the BearingFrameLayout
} // end method onStart
// called when Activity is no longer visible to the user
@Override
public void onStop()
{
super.onStop(); // call the super method
wakeLock.release(); // release the wakelock
} // end method onStop
// update location on map
public void updateLocation(Location location)
{
if (location != null && gpsFix) // location not null; have GPS fix
{
// add the given Location to the route
routeOverlay.addPoint(location);
// if there is a previous location
if (previousLocation != null)
{
// add to the total distanceTraveled
distanceTraveled += location.distanceTo(previousLocation);
} // end if
// get the latitude and longitude
Double latitude = location.getLatitude() * 1E6;
Double longitude = location.getLongitude() * 1E6;
// create GeoPoint representing the given Locations
GeoPoint point =
new GeoPoint(latitude.intValue(), longitude.intValue());
// move the map to the current location
mapController.animateTo(point);
// update the compass bearing
bearingFrameLayout.setBearing(location.getBearing());
bearingFrameLayout.invalidate(); // redraw based on bearing
} // end if
previousLocation = location;
} // end method updateLocation
// responds to events from the LocationManager
private final LocationListener locationListener =
new LocationListener()
{
// when the location is changed
public void onLocationChanged(Location location)
{
gpsFix = true; // if getting Locations, then we have a GPS fix
if (tracking) // if we're currently tracking
updateLocation(location); // update the location
} // end onLocationChanged
public void onProviderDisabled(String provider)
{
} // end onProviderDisabled
public void onProviderEnabled(String provider)
{
} // end onProviderEnabled
public void onStatusChanged(String provider,
int status, Bundle extras)
{
} // end onStatusChanged
}; // end locationListener
// determine whether we have GPS fix
GpsStatus.Listener gpsStatusListener = new GpsStatus.Listener()
{
public void onGpsStatusChanged(int event)
{
if (event == GpsStatus.GPS_EVENT_FIRST_FIX)
{
gpsFix = true;
Toast results = Toast.makeText(RouteTracker.this,
getResources().getString(R.string.toast_signal_acquired),
Toast.LENGTH_SHORT);
// center the Toast in the screen
results.setGravity(Gravity.CENTER,
results.getXOffset() / 2, results.getYOffset() / 2);
results.show(); // display the results
} // end if
} // end method on GpsStatusChanged
}; // end anonymous inner class
// Google terms of use require this method to return
// true if you're displaying route information like driving directions
@Override
protected boolean isRouteDisplayed()
{
return false; // we aren't displaying route information
} // end method isRouteDisplayed
// create the Activity's menu from a menu resource XML file
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.route_tracker_menu, menu);
return true;
} // end method onCreateOptionsMenu
// handle choice from options menu
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
// perform appropriate task based on
switch (item.getItemId())
{
case R.id.mapItem: // the user selected "Map"
mapView.setSatellite(false); // display map image
return true;
case R.id.satelliteItem: // the user selected "Satellite"
mapView.setSatellite(true); // display satellite image
return true;
default:
return super.onOptionsItemSelected(item);
} // end switch
} // end method onOptionsItemSelected
// listener for trackingToggleButton's events
OnCheckedChangeListener trackingToggleButtonListener =
new OnCheckedChangeListener()
{
// called when user toggles tracking state
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked)
{
// if app is currently tracking
if (!isChecked)
{
tracking = false; // just stopped tracking locations
// compute the total time we were tracking
long milliseconds = System.currentTimeMillis() - startTime;
double totalHours = milliseconds / MILLISECONDS_PER_HOUR;
// create a dialog displaying the results
AlertDialog.Builder dialogBuilder =
new AlertDialog.Builder(RouteTracker.this);
dialogBuilder.setTitle(R.string.results);
double distanceKM = distanceTraveled / 1000.0;
double speedKM = distanceKM / totalHours;
double distanceMI = distanceKM * MILES_PER_KILOMETER;
double speedMI = distanceMI / totalHours;
// display distanceTraveled traveled and average speed
dialogBuilder.setMessage(String.format(
getResources().getString(R.string.results_format),
distanceKM, distanceMI, speedKM, speedMI));
dialogBuilder.setPositiveButton(
R.string.button_ok, null);
dialogBuilder.show(); // display the dialog
} // end if
else
{
tracking = true; // app is now tracking
startTime = System.currentTimeMillis(); // get current time
routeOverlay.reset(); // reset for new route
bearingFrameLayout.invalidate(); // clear the route
previousLocation = null; // starting a new route
} // end else
} // end method onCheckChanged
}; // end anonymous inner class
} // end class RouteTracker
// RouteOverlay.java
// Draws route on MapView.
package com.deitel.routetracker;
import java.util.ArrayList;
import java.util.List;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.location.Location;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
public class RouteOverlay extends Overlay
{
private List<Location> locations; // stores Location tracking data
private Paint pathPaint; // Paint information for the Path
private Paint positionPaint; // Paint information for current position
private final int POSITION_MARKER = 10; // marker frequency
public RouteOverlay()
{
// Paint for drawing Path as a red line with a width of 5
pathPaint = new Paint();
pathPaint.setAntiAlias(true);
pathPaint.setColor(Color.RED);
pathPaint.setStyle(Paint.Style.STROKE);
pathPaint.setStrokeWidth(5);
locations = new ArrayList<Location>(); // initialize points
// Paint for drawing black circle every POSITION_MARKER Locations
positionPaint = new Paint();
positionPaint.setAntiAlias(true);
positionPaint.setStyle(Paint.Style.FILL);
} // end RouteOverlay constructor
// add new Location to List of Locations
public void addPoint(Location location)
{
locations.add(location);
} // end method addPoint
// reset the Overlay for tracking a new route
public void reset()
{
locations.clear(); // delete all prior Locations
} // end method reset
// draw this Overlay on top of the given MapView
@Override
public void draw(Canvas canvas, MapView mapView, boolean shadow)
{
super.draw(canvas, mapView, shadow); // call super's draw method
Path newPath = new Path(); // get a new Path
Location previous = null; // initialize previous Location to null
// for each Location
for (int i = 0; i < locations.size(); ++i)
{
Location location = locations.get(i);
// convert Location to GeoPoint
Double newLatitude = location.getLatitude() * 1E6;
Double newLongitude = location.getLongitude() * 1E6;
GeoPoint newPoint = new GeoPoint(newLatitude.intValue(),
newLongitude.intValue());
// convert the GeoPoint to point on the screen
Point newScreenPoints = new Point();
mapView.getProjection().toPixels(newPoint, newScreenPoints);
if (previous != null) // if this is not the first Location
{
// get GeoPoint for the previous Location
Double oldLatitude = previous.getLatitude() * 1E6;
Double oldLongitude = previous.getLongitude() * 1E6;
GeoPoint oldPoint = new GeoPoint(oldLatitude.intValue(),
oldLongitude.intValue());
// convert the GeoPoint to point on the screen
Point oldScreenPoints = new Point();
mapView.getProjection().toPixels(oldPoint, oldScreenPoints);
// add the new point to the Path
newPath.quadTo(oldScreenPoints.x, oldScreenPoints.y,
(newScreenPoints.x + oldScreenPoints.x) / 2,
(newScreenPoints.y + oldScreenPoints.y) / 2);
// possibly draw a black dot for current position
if ((i % POSITION_MARKER) == 0)
canvas.drawCircle(newScreenPoints.x, newScreenPoints.y, 10,
positionPaint);
} // end if
else
{
// move to the first Location
newPath.moveTo(newScreenPoints.x, newScreenPoints.y);
} // end else
previous = location; // store location
} // end for
canvas.drawPath(newPath, pathPaint); // draw the path
} // end method draw
} // end class RouteOverlay
// BearingFrameLayout.java
// Rotates MapView according to device's bearing.
package com.deitel.routetracker;
import com.google.android.maps.MapView;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.view.Display;
import android.widget.FrameLayout;
public class BearingFrameLayout extends FrameLayout
{
private int scale = 0; // amount to scale layout
private MapView mapView; // displays Google maps
private float bearing = 0f; // compass bearing
// returns layout parameters for MapView
public LayoutParams getChildLayoutParams()
{
Display display =
((Activity) getContext()).getWindowManager().getDefaultDisplay();
int w = display.getWidth();
int h = display.getHeight();
scale = (int) Math.sqrt((w * w) + (h * h));
return new LayoutParams(scale, scale);
} // end method getChildLayoutParams
// public constructor for BearingFrameLayout
public BearingFrameLayout(Context context, String apiKey)
{
super(context); // call super constructor
mapView = new MapView(context, apiKey); // create new MapView
mapView.setClickable(true); // allow user interactions with the map
mapView.setEnabled(true); // enables the MapView to generate events
mapView.setSatellite(false); // display map image
mapView.setBuiltInZoomControls(true); // enable zoom controls
// set MapView's layout
mapView.setLayoutParams(getChildLayoutParams());
addView(mapView); // add MapView to this layout
} // end BearingFrameLayout constructor
// rotates the map according to bearing
@Override
protected void dispatchDraw(Canvas canvas)
{
if (bearing >= 0) // if the bearing is greater than 0
{
// get canvas dimensions
int canvasWidth = canvas.getWidth();
int canvasHeight = canvas.getHeight();
// dimensions of the scaled canvas
int width = scale;
int height = scale;
// center of scaled canvas
int centerXScaled = width / 2;
int centerYScaled = height / 2;
// center of screen canvas
int centerX = canvasWidth / 2;
int centerY = canvasHeight / 2;
// move center of scaled area to center of actual screen
canvas.translate(-(centerXScaled - centerX),
-(centerYScaled - centerY));
// rotate around center of screen
canvas.rotate(-bearing, centerXScaled, centerYScaled);
} // end if
super.dispatchDraw(canvas); // draw child Views of this layout
} // end method dispatchDraw
// set the compass bearing
public void setBearing(float bearing)
{
this.bearing = bearing;
} // end method setCompassBearing
// return the MapView
public MapView getMapview()
{
return mapView;
} // end method getMapView
} // end class BearingFrameLayout