I'm trying to animate a new location on the map when the location changed (or when I supply a mock location via the telnet)
this is what I use
Toast.makeText(getApplicationContext(), "New Lontitue = "+ lontitue +"\n New Latitute = "+ latitute, Toast.LENGTH_LONG).show();
GeoPoint geopoint = new GeoPoint(latitute, lontitue);
mapController.animateTo(geopoint);
Though the Toast shows the lontitute and latitute properly, app doesn't animate to given cordinates. What could be the problem?? Please find my whole code below.
package com.mayuonline.androidgps;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;
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 GPSActivity extends MapActivity {
MapController mapController;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// setting up map
MapView mapview = (MapView)findViewById(R.id.mapview);
mapview.setBuiltInZoomControls(true);
mapController = mapview.getController();
// mapController.setZoom(16);
LocationManager locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
makeUseOfNewLocation(location);
//Toast.makeText(getApplicationContext(), "New Locationdd", Toast.LENGTH_LONG).show();
}
private void makeUseOfNewLocation(Location location) {
double lon = (double)location.getLongitude();
double lat = (double)location.getLatitude();
int lontitue = (int)lon;
int latitute = (int)lat;
Toast.makeText(getApplicationContext(), "New Lontitue = "+ lontitue +"\n New Latitute = "+ latitute, Toast.LENGTH_LONG).show();
GeoPoint geopoint = new GeoPoint(latitute, lontitue);
mapController.animateTo(geopoint);
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,locationListener);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
}
I figured out the issue. It is something to do with getLongitude method :)
I need to multiply by 1E6 as given below.
double lon = (double) (location.getLongitude() * 1E6);
double lat = (double) (location.getLatitude() * 1E6);
int lontitue = (int)lon;
int latitute = (int)lat;
Toast.makeText(getApplicationContext(), "New Lontitue = "+ lontitue +"\n New Latitute = "+ latitute, Toast.LENGTH_LONG).show();
GeoPoint geopoint = new GeoPoint(latitute, lontitue);
mapController.animateTo(geopoint);
You need to add mapview.invalidate(); after your mapController.animateTo(geopoint) like this
GeoPoint geopoint = new GeoPoint(latitute, lontitue);
mapController.animateTo(geopoint);
mapview.invalidate();
That should work!
Related
I am trying to make a background service which runs even when app is closed, it would get current location and once person is close to destination the app would start up.
package als.wakeup;
import com.google.android.gms.maps.model.LatLng;
import android.app.Service;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class Awake_Alarm extends Service implements LocationListener{
Location location;
ConversePrefs cp;
ConversePrefs_sets cpss;
LatLng final_dest;
Settings sets;
double final_range;
LocationManager locationManager;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
final String provider = locationManager.getBestProvider(criteria, true);
location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 20000, 0, this);
cp = new ConversePrefs(this);
cpss = new ConversePrefs_sets(this);
sets = new Settings(this);
final_range = cp.GetIntSetting("Range", 250);
final_dest = cp.GetCoords();
if(cpss.GetIntSetting(sets.def_units_name, 0) == 1){
final_range = final_range * 1.09361;
}
Toast.makeText(getApplicationContext(), "Started", Toast.LENGTH_LONG).show();
Log.d("STATUS", "RUNNING");
super.onCreate();
}
public double distanceGet(LatLng StartP, LatLng EndP) {
double lat1 = StartP.latitude;
double lat2 = EndP.latitude;
double lon1 = StartP.longitude;
double lon2 = EndP.longitude;
double dLat = Math.toRadians(lat2-lat1);
double dLon = Math.toRadians(lon2-lon1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2);
double c = 2 * Math.asin(Math.sqrt(a));
return 6366000 * c;
}
#Override
public void onLocationChanged(Location arg0) {
LatLng me = new LatLng(location.getLatitude(), location.getLongitude());
double dest = distanceGet(me, final_dest);
if(dest <= final_range){
Toast.makeText(getApplicationContext(), String.valueOf(dest)+" Away-.", Toast.LENGTH_LONG).show();
Log.d("STATUS", "RUNNING-"+String.valueOf(dest));
}
Toast.makeText(getApplicationContext(), String.valueOf(dest)+" Away2-.", Toast.LENGTH_LONG).show();
Log.d("STATUS", "RUNNING2-"+String.valueOf(dest));
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
It seems to work fine, it launches etc and runs, and when location is changed it makes Toast text as required, but: The distance to target doesn't get updated, say I launch app, click start service and distance to destination is 1500 Meters, when location gets changed it still makes toast text saying: "1500 meters"
What am I doing wrong?
This is my Map Activity class and i have to extract the current location lat n long points and have to show them on map.And i also have incorporated a search box which will display the location of an address on map. Its showing the location but at difference of 200 meter. And when i reopen it, it always show the previous traced location or searched location. I want to show the extracted lat n long points on map.Please Help me out. Thanks in advance..
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.AlertDialog;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Criteria;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
public class MapViewActivity extends MapActivity implements LocationListener {
private MapView mapView;
Button search;
EditText address;
private LocationManager locationManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
search=(Button)findViewById(R.id.find_loc);
address=(EditText)findViewById(R.id.enter_address);
search.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
address=(EditText)findViewById(R.id.enter_address);
if (address.getText().toString().trim().length() == 0) {
showMessage("Error", "Please enter address!");
return;
}
Geocoder geoCoder = new Geocoder(MapViewActivity.this,
Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocationName(
address.getText().toString(), 1);
// Getting latitude
double latitude = addresses.get(0).getLatitude();
// Getting longitude
double longitude = addresses.get(0).getLongitude();
if (addresses.size() > 0) {
GeoPoint p = new GeoPoint(
(int) ( latitude * 1E6),
(int) (longitude * 1E6));
// Getting MapController
MapController mapController =
mapView.getController();
// Locating the Geographical point in the Map
mapController.animateTo(p);
//Applying a zoom
mapController.setZoom(15);
// Redraw the map
mapView.invalidate();
// Getting list of overlays available in the map
List<Overlay> mapOverlays = mapView.getOverlays();
// Creating a drawable object to represent the
image of mark in the map
Drawable drawable =
MapViewActivity.this.getResources().getDrawable(R.drawable.cur_position);
// Creating an instance of ItemizedOverlay to mark
the current location in the map
CurrentLocationOverlay currentLocationOverlay = new
CurrentLocationOverlay(drawable);
// Creating an item to represent a mark in the
overlay
OverlayItem currentLocation = new OverlayItem(p,
"Current Location", "Latitude : " + latitude + ", Longitude:" + longitude);
// Adding the mark to the overlay
currentLocationOverlay.addOverlay(currentLocation);
// Clear Existing overlays in the map
mapOverlays.clear();
// Adding new overlay to map overlay
mapOverlays.add(currentLocationOverlay);
}
} catch (IOException e) {
e.printStackTrace();
}
catch(Exception e)
{
showMessage("Error", "Address not found!");
e.printStackTrace();
}
}
});
// Getting reference to MapView
mapView = (MapView) findViewById(R.id.map_view);
// Setting Zoom Controls on MapView
mapView.setBuiltInZoomControls(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
//Criteria criteria = new Criteria();
final Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
#Override
public void onBackPressed() {
finish();
}
#Override
public void onDestroy() {
if (locationManager != null) {
locationManager.removeUpdates(this);
}
super.onDestroy();
}
#Override
public void onLocationChanged(Location location) {
// Getting latitude
double latitude = location.getLatitude();
// Getting longitude
double longitude = location.getLongitude();
// Setting latitude and longitude in the TextView tv_location
//tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude
);
// Creating an instance of GeoPoint corresponding to latitude and longitude
GeoPoint point = new GeoPoint((int)(latitude * 1E6), (int)(longitude*1E6));
// Getting MapController
MapController mapController = mapView.getController();
// Locating the Geographical point in the Map
mapController.animateTo(point);
// Applying a zoom
mapController.setZoom(15);
// Redraw the map
mapView.invalidate();
// Getting list of overlays available in the map
List<Overlay> mapOverlays = mapView.getOverlays();
// Creating a drawable object to represent the image of mark in the map
Drawable drawable =
this.getResources().getDrawable(R.drawable.cur_position);
// Creating an instance of ItemizedOverlay to mark the current location in
the map
CurrentLocationOverlay currentLocationOverlay = new
CurrentLocationOverlay(drawable);
// Creating an item to represent a mark in the overlay
OverlayItem currentLocation = new OverlayItem(point, "Current Location",
"Latitude : " + latitude + ", Longitude:" + longitude);
// Adding the mark to the overlay
currentLocationOverlay.addOverlay(currentLocation);
// Clear Existing overlays in the map
mapOverlays.clear();
// Adding new overlay to map overlay
mapOverlays.add(currentLocationOverlay);
}
private void showMessage(final String title, final String message) {
runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder alert = new AlertDialog.Builder(MapViewActivity.this);
alert.setTitle(title);
alert.setPositiveButton("OK", null);
alert.setMessage(message);
alert.show();
}
});
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
and this is my CurrentLocationOverlay class
package com.ceolution.bhinstitute.crm;
import java.util.ArrayList;
import android.graphics.drawable.Drawable;
import android.util.Log;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;
public class CurrentLocationOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
public CurrentLocationOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
// Executed, when populate() method is called
#Override
protected OverlayItem createItem(int arg0) {
return mOverlays.get(arg0);
}
#Override
public int size() {
return mOverlays.size();
}
public void addOverlay(OverlayItem overlay){
mOverlays.add(overlay);
populate(); // Calls the method createItem()
}
#Override
protected boolean onTap(int arg0) {
Log.d("Tapped", mOverlays.get(arg0).getSnippet());
return true;
}
}
// Getting LocationManager object from System Service LOCATION_SERVICE
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
String provider;
if(!isGPSEnabled)
{
provider = LocationManager.NETWORK_PROVIDER;
}
else
provider=LocationManager.GPS_PROVIDER;
locationManager.requestLocationUpdates(provider, 20000, 0, this);
use above code after
// Setting Zoom Controls on MapView
mapView.setBuiltInZoomControls(true);
hope this will help and also you can give alert to user to enable gps.
I am trying to get coordinates from GPS (this actually gives the values for lat and long on a Toast.) i am trying to get that values and use it as Map coordinates and to show the current location but it is not showing it. where have i gone wrong?
public class Map extends MapActivity {
MapController mControl;
GeoPoint GeoP;
MapView mapV;
public double lat;
public double longi;
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
protected LocationManager locationManager;
#Override
public void onCreate (Bundle saveInstanceState){
super.onCreate(saveInstanceState);
setContentView(R.layout.map);
mapV = (MapView)findViewById(R.id.mapview);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationListener()
);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
lat = location.getLatitude();
longi = location.getLongitude();
}
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(Map.this, message, Toast.LENGTH_LONG).show();
GeoP = new GeoPoint ((int)(lat*1E6),(int)(longi * 1E6));
mControl = mapV.getController();
mControl.animateTo(GeoP);
mControl.setZoom(13);
}
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(Map.this, message, Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
I wonder why your are not tring to display location in onLocationChanged Callback.
When any time your device fetch some location this method gets called at first.
So include following code in onLocationChanged
It should be something like this.
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude() * 1E6);
int lng = (int) (location.getLongitude() * 1E6);
GeoPoint point = new GeoPoint(lat, lng);
mControl.animateTo(point); // mapController.setCenter(point);
}
Hey i have implemented using this site as an example please look at this it might help you out
http://mobiforge.com/developing/story/using-google-maps-android
http://www.vogella.com/articles/AndroidLocationAPI/article.html
package m.a.p;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationListener;
import android.os.Bundle;
import android.widget.Toast;
public class MappingActivity extends MapActivity {
/** Called when the activity is first created. */
MapController mControl;
GeoPoint GeoP;
MapView mapV;
public double lat;
public double lng;
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
protected LocationManager locationManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapV = (MapView) findViewById(R.id.mapview);
// double lat = 40.8;
// double lng = -96.66;
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationListener()
);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
}
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
lat, lng
);
Toast.makeText(MappingActivity.this, message, Toast.LENGTH_LONG).show();
GeoP = new GeoPoint ((int)(lat*1E6),(int)(lng * 1E6));
// GeoP = new GeoPoint ((int)(lat * 1E6),(int)(lng*1E6));
mControl = mapV.getController();
mControl.animateTo(GeoP);
mControl.setZoom(13);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
public class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
lat, lng
);
Toast.makeText(MappingActivity.this, message, Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
Thank you every one for the help. it worked finally
I want to explore my cities on a mapview with multiple annotations but I unable to do that. Is any one suggest me that how can we do this in android with user defined longitude and latitude. I created a map view with one annotation but with system defined, I have to pass longitude and latitude from emulator control. how we send that with code with multiple annotation.
Here is my code:
package com.ex.maps;
import java.util.List;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Toast;
import android.widget.ZoomControls;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
public class HelloGoogleMaps extends MapActivity implements LocationListener{
MapController mc;
GeoPoint p;
double lat;
double lng;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MapView gMapView = (MapView) findViewById(R.id.mapview);
gMapView.setBuiltInZoomControls(true);
GeoPoint p = new GeoPoint((int) (lat * 1000000), (int) (lng * 1000000));
gMapView.setSatellite(true);
mc = gMapView.getController();
mc.setCenter(p);
mc.setZoom(14);
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new HelloGoogleMaps();
//lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,mlocListener );
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f, this);
ZoomControls zoomControls = (ZoomControls) gMapView.getZoomControls();
zoomControls.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
gMapView.addView(zoomControls);
gMapView.displayZoomControls(true);
MyLocationOverlay myLocationOverlay = new MyLocationOverlay();
List<Overlay> list = gMapView.getOverlays();
list.add(myLocationOverlay);
/*List<Overlay> mapOverlays = gMapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.arrow_icon);
HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable);
//GeoPoint p = new GeoPoint((int) (lat * 1000000), (int) (lng * 1000000));
OverlayItem overlayitem = new OverlayItem(point, "Hola, Mundo!", "I'm in Mexico City!");
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);*/
}
public void onLocationChanged(Location location) {
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
p = new GeoPoint((int) (lat * 1000000), (int) (lng * 1000000));
mc.animateTo(p);
//Log.d("LOCATION CHANGED", location.getLatitude() + "");
//Log.d("LOCATION CHANGED", location.getLongitude() + "");*/
Toast.makeText(HelloGoogleMaps.this,
location.getLatitude() + "" + location.getLongitude(),
Toast.LENGTH_LONG).show();
}
}
//makeUseOfNewLocation(location);
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
protected boolean isRouteDisplayed() {
return true;
}
class MyLocationOverlay extends com.google.android.maps.Overlay {
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {
super.draw(canvas, mapView, shadow);
Paint paint = new Paint();
// Converts lat/lng-Point to OUR coordinates on the screen.
Point myScreenCoords = new Point();
mapView.getProjection().toPixels(p, myScreenCoords);
paint.setStrokeWidth(1);
paint.setARGB(255, 255, 255, 255);
paint.setStyle(Paint.Style.STROKE);
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
canvas.drawBitmap(bmp, myScreenCoords.x, myScreenCoords.y, paint);
canvas.drawText("Here I am...", myScreenCoords.x, myScreenCoords.y, paint);
return true;
} }
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favmapview);
listbtn = (Button)findViewById(R.id.button1);
mapbtn = (Button)findViewById(R.id.button2);
TextView tv = (TextView)findViewById(R.id.tvmap);
bundle = getIntent().getExtras();
str1= bundle.getString("key");
lat = bundle.getStringArrayList("lat");
log=bundle.getStringArrayList("log");
location = bundle.getStringArrayList("location");
tv.setText(str1);
listbtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
OpenListView(); // Function called to display list view
}
});
initialiseMapView();
}
// Navigates to listView class and displays listView
protected void OpenListView() {
final ProgressDialog dialog = ProgressDialog.show(FavMapView.this, "HIV ATLAS",
"Please wait...", true);
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
dialog.dismiss();
}
};
Thread checkUpdate = new Thread() {
public void run() {
Intent intent = new Intent(FavMapView.this,Favorites.class);
intent.putExtra("key", bundle.getString("key"));
startActivity(intent);
dialog.dismiss();
handler.sendEmptyMessage(0);
}
};
checkUpdate.start();
}
//============End
#Override
public boolean isRouteDisplayed() {
return true;
}
//Generates Map View
private void initialiseMapView() {
mapView = (MapView) findViewById(R.id.mapview);
mapController = mapView.getController();
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(false);
GeoPoint startPoint = new GeoPoint((int)(40.7575 * 1E6), (int)(-73.9785 * 1E6));
mapController.setCenter(startPoint);
}
//===============End
#Override
public void onStart() {
super.onStart();
initialiseOverlays();
}
// Sets Geo points on Map View
private void initialiseOverlays() {
try {
// Create an ItemizedOverlay to display a list of markers
Drawable defaultMarker = getResources().getDrawable(R.drawable.marker);
placesItemizedOverlay = new HelloItemizedOverlay (FavMapView.this, defaultMarker);
for(int i=0;i<log.size();i++)
{
double lat1 = Double.parseDouble(lat.get(i));
double log1 =Double.parseDouble(log.get(i));
placesItemizedOverlay.addOverlayItem(new OverlayItem(new GeoPoint((int)(lat1 * 1E6),
(int) (log1 * 1E6)),location.get(i),null));
}
//==============================End
// Add the overlays to the map
mapView.getOverlays().add(placesItemizedOverlay);
} catch (NumberFormatException e) {
Toast.makeText(getApplicationContext(), "No Jobs available",
Toast.LENGTH_SHORT).show();
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NotFoundException e) {
Toast.makeText(getApplicationContext(), "No Jobs available",
Toast.LENGTH_SHORT).show();
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
when i extends the MapActivity class it shows an error.
error is:
cant resolved datatype. why?
how to add a maps.jar in my project?
thanks.
You probably haven't done the steps required to set up a Maps project as described in Maps External API Overview. There is no maps.jar to add. Read the document I linked to, and you should be all set.
Google Map View :
Creating a Map Activity
Here is my code :
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.content.Context;
import android.graphics.Canvas;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
public class MyMapsActivity extends MapActivity
{
MapView mapView;
MapController mapController;
LocationManager locationManager;
LocationListener locationListener;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapView);
// enable Street view by default
mapView.setStreetView(true);
// enable to show Satellite view
// mapView.setSatellite(true);
// enable to show Traffic on map
// mapView.setTraffic(true);
mapView.setBuiltInZoomControls(true);
mapController = mapView.getController();
mapController.setZoom(5);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new GPSLocationListener();
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
0,
0,
locationListener);
Touchy t = new Touchy();
List<Overlay> overlayList = mapView.getOverlays();
overlayList.add(t);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
class Touchy extends Overlay
{
public boolean onTap(GeoPoint point, MapView mapView)
{
Context contexto = mapView.getContext();
String msg = "Latitude : " + point.getLatitudeE6()/1E6 + " - " +
"Longitude : " + point.getLongitudeE6()/1E6;
Toast toast = Toast.makeText(contexto, msg, Toast.LENGTH_SHORT);
toast.show();
return true;
}
}
private class GPSLocationListener implements LocationListener
{
public void onLocationChanged(Location location)
{
if (location != null)
{
GeoPoint point = new GeoPoint(
(int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6));
Toast.makeText(getBaseContext(),
"Latitude: " + location.getLatitude() +
" Longitude: " + location.getLongitude(),
Toast.LENGTH_SHORT).show();
mapController.animateTo(point);
mapController.setZoom(5);
mapView.invalidate();
}
if (location != null)
{
GeoPoint point=null;
String address = ConvertPointToLocation(point);
Toast.makeText(getBaseContext(), address, Toast.LENGTH_SHORT).show();
}
}
public String ConvertPointToLocation(GeoPoint point) {
String address = "";
Geocoder geoCoder = new Geocoder(
getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
point.getLatitudeE6() / 1E6,
point.getLongitudeE6() / 1E6, 1);
if (addresses.size() > 0) {
for (int index = 0;
index < addresses.get(0).getMaxAddressLineIndex(); index++)
address += addresses.get(0).getAddressLine(index) + " ";
}
}
catch (IOException e) {
e.printStackTrace();
}
return address;
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
Layout Coding :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.google.android.maps.MapView
android:id="#+id/mapView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:enabled="true"
android:clickable="true"
android:apiKey="Your MAP API Key"
/>
<LinearLayout android:id="#+id/zoom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
/>
</RelativeLayout>
Link for getting own API key process :
http://sanathnandasiri.blogspot.in/2011/04/obtaining-google-maps-api-key-for.html