adding path between two overlay items using GPS Android - android

package ntryn.n;
import java.util.List;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
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;
import com.google.android.maps.OverlayItem;
public class ntryn extends MapActivity
{
private MapView mapView;
private MapController mc;
GeoPoint p, p2, p3, p4;
List<Overlay> mapOverlays;
Drawable drawable, drawable2 , drawable3, drawable4;
HelloItemizedOverlay itemizedOverlay, itemizedOverlay2 , itemizedOverlay3, itemizedOverlay4;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
try{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/* Use the LocationManager class to obtain GPS locations */
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
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);
mc = mapView.getController();
//mapView.setStreetView(true);
//mapView.setSatellite(true);
mc.setZoom(12);
addOverLays();
}
catch(Exception e){
Log.d("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",e.getMessage());
}
}
public void addOverLays(){
String [] coordinates = {"30.084262490272522","31.33625864982605" ,"30.084123015403748", "51.5002" , "-0.1262","31.337149143218994"};
double lat = 30.084262490272522, lat2 = 51.5002,lat3=29.987091422080994;
double log = 31.33625864982605, log2 = -0.1262,log3=31.43909454345703;
p = new GeoPoint((int) (lat * 1E6), (int) (log * 1E6));
p2 = new GeoPoint( (int) (lat2 * 1e6), (int) (log2 * 1e6));
p3=new GeoPoint( (int) (lat3 * 1e6), (int) (log3 * 1e6));
mapOverlays = mapView.getOverlays();
drawable = this.getResources().getDrawable(R.drawable.ballon);
drawable2 = this.getResources().getDrawable(R.drawable.ballon);
drawable3 = this.getResources().getDrawable(R.drawable.ballon);
itemizedOverlay = new HelloItemizedOverlay(drawable,this);
itemizedOverlay2 = new HelloItemizedOverlay(drawable2,this);
itemizedOverlay3 = new HelloItemizedOverlay(drawable3,this);
OverlayItem overlayitem = new OverlayItem(p, "Cairo", " over1");
OverlayItem over2 = new OverlayItem(p2, "ulm", "over2");
OverlayItem over3 = new OverlayItem(p3, "offff", "over3");
itemizedOverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedOverlay);
itemizedOverlay2.addOverlay(over2);
mapOverlays.add(itemizedOverlay2);
itemizedOverlay3.addOverlay(over3);
mapOverlays.add(itemizedOverlay3);
mc.setZoom(17);
//mc.animateTo(p);
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
GeoPoint point = new GeoPoint( (int) (loc.getLatitude() * 1E6),
(int) (loc.getLongitude() * 1E6));
//DoubletoString(loc.getLatitude());
//DoubletoString(loc.getLongitude());
String Text = "My current location is: " +
"Latitud ="+ loc.getLatitude() +
"Longitud =" + loc.getLongitude();
Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_SHORT).show();
mc.animateTo(point);
}
private void DoubletoString(double latitude) {
// TODO Auto-generated method stub
}
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
}
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) { }
protected boolean isRouteDisplayed() {
return false;
}
}/* End of Class MyLocationListener */
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
// i want to add path between this two overlay items

I think what you want to know is: if you have an overlay with two GeoPoints in it, how do you have the overlay draw a line between the two points?
In the draw() method of your Overlay subclass, you would do something like the following:
#Override
public void draw(android.graphics.Canvas canvas, MapView mapView, boolean shadow)
{
GeoPoint point1, point2;
// Let's assume you've assigned values to these two GeoPoints now.
Projection projection = mapView.getProjection();
Point startingPoint = projection.toPixels(point1, null);
Point endingPoint = projection.toPixels(point2, null);
// Create the path containing the line between the two points.
Path path = new Path();
path.moveTo(startingPoint.x, startingPoint.y);
path.lineTo(endingPoint.x, endingPoint.y);
// Setup the paint. You'd probably do this outside of the draw() method to be more efficient.
Paint paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
// Can set other paint characteristics, such as width, anti-alias, color, etc....
// Draw the path!
canvas.drawPath(path, paint);
}

Related

How to store GPS Location in SharedPreferences Android

I have five fixed GPS locations in my application. When you come near them, it will be stored in the application and unlock a medal of some sort. I have used SharedPreferences for my quiz and medals, but I am a little unsure on how to store GPS in SharedPreferences as well. This is my code so far.
package com.example.norskattraksjon;
import java.util.ArrayList;
import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import com.google.android.maps.GeoPoint;
public class MyLocationListener implements LocationListener {
private ArrayList<GeoPoint> gplist;
public MyLocationListener(ArrayList<GeoPoint> gpList2) {
gplist = gpList2;
}
public void onLocationChanged(Location location) {
System.out.println("Den kommer hits");
for(GeoPoint gp : gplist){
//SÂ henter vi ut latitude og longitude.
//Det forvirrende her er at klassen "Location" bruker float-koordinater
//mens "GeoPoint" bruker mikrokoordinater. Dermed m man konvertere mellom de.
float latitude = (float) (gp.getLatitudeE6() / 1E6);
float longitude = (float) (gp.getLongitudeE6() / 1E6);
//Vi lager en "location" for hvert av punktene i gplist, utifra latitude og longitude.
Location test = new Location("tester");
test.setLatitude(latitude);
test.setLongitude(longitude);
//location.distanceTo() er en metode som sjekker avstanden til punkter.
//Her skal distansen vÊre under 10 000 meter.
if(location.distanceTo(test) <= 70){
//Om distansen er under 10 000m, s lager du en toast som gir den faktiske avstanden til punktet.
System.out.println("Her er du");
SharedPreferences prefs = getSharedPreferences("com.example.norskattraksjon",
Context.MODE_PRIVATE);
// Lagre en tekst... først trenger vi en editor
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("location", true);
//Lagrer verdien
editor.commit();
};
}
};
private SharedPreferences getSharedPreferences(String string,
int modePrivate) {
// TODO Auto-generated method stub
return null;
}
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
}
}
And this is my other coherent code;
package com.example.norskattraksjon;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
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 MainActivityMap extends MapActivity {
private MapController mc;
MapOverlays overlay;
ArrayList<GeoPoint> gplist;
List<Overlay> overlayList;
LocationListener mlocListener; //Denne klassen lytter etter lokasjonen din
LocationManager mlocManager; //Mens denne kobler deg opp mot telefonens GPS.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println("WEEEEEEE");
setContentView(R.layout.mapview);
MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(true);
mc = mapView.getController();
gplist = new ArrayList<GeoPoint>();
overlayList = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.ic_launcher);
overlay = new MapOverlays(drawable, this);
double lat = 60.39403;
double lon = 5.330579;
GeoPoint point = new GeoPoint ((int) (lat * 1E6), (int) (lon*1E6));
gplist.add(point);
OverlayItem punkt1 = new OverlayItem(point, "Du har kommet til!", "Domkyrkja i Bergen!");
double lat2 = 60.702251;
double lon2 = 5.333685;
GeoPoint point1 = new GeoPoint ((int) (lat2 * 1E6), (int) (lon2 *1E6));
gplist.add(point1);
OverlayItem punkt2 = new OverlayItem(point1, "Her ble", "Noen som drepte kongen begravd");
double lat3 = 60.37829;
double lon3 = 5.335665;
GeoPoint point3 = new GeoPoint ((int) (lat3 * 1E6), (int) (lon3 *1E6));
gplist.add(point3);
OverlayItem punkt3 = new OverlayItem(point3, "Her ble", "Himmelfarten med tran i maga!");
double lat4 = 60.213789;
double lon4 = 5.369895;
GeoPoint point4 = new GeoPoint ((int) (lat4 * 1E6), (int) (lon4 *1E6));
gplist.add(point4);
OverlayItem punkt4 = new OverlayItem(point4, "Her ble", "Flygelet skapt");
double lat5 = 60.413619;
double lon5 = 5.37579;
GeoPoint point5 = new GeoPoint ((int) (lat5 * 1E6), (int) (lon5 *1E6));
gplist.add(point5);
OverlayItem punkt5 = new OverlayItem(point5, "Her ble", "Bergensbakken bakt");
overlay.addOverlay(punkt1);
overlay.addOverlay(punkt2);
overlay.addOverlay(punkt3);
overlay.addOverlay(punkt4);
overlay.addOverlay(punkt5);
overlayList.add(overlay);
mc.animateTo(point);
mc.setZoom(11);
//Dette er metoden man bruker for  koble opp til mobilens GPS
mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
//Her lager vi en instans av vÂr egen LocationListener. Dette gj¯r at vi kan bestemme selv hva som skjer
//nÂr man trykker p overlays.
mlocListener = new MyLocationListener(gplist);
//Her sier vi at vÂr LocationListener skal sp¯rre om GPS-signaler fra en GPS_PROVIDER.
//0 stÂr for minimumstiden mellom oppdateringer
//Den andre 0 stÂr for minimumsdistansen mellom oppdateringer
//mLocListener er instansen vi lagde av vÂr egen LocationListener.
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
}
public GeoPoint newGeo(double x, double y){
int a = (int) (x * 1E6);
int b = (int) (y * 1E6);
GeoPoint z = new GeoPoint(a,b);
return z;
}
#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;
}
}
SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context);
int latE6 = (int) (lat * 1e6);
int lonE6 = (int) (lon * 1e6);
p.edit().putInt("Lat", latE6).commit();
p.edit().putInt("Long", lonE6).commit();
In the above code lat and lon are your location's latitude and longitude. then you can retrieve them as int variables and get location values by dividing them by 1e6 again.
int lat= p.getInt("Lat", "");
int lon = p.getInt("Long", "");
You can store the Lat and Long directly in the SharedPreference as follows:
SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context);
p.edit().putString("Lat", YOUR_LATTITUDE).commit();
p.edit().putString("Long", YOUR_LONGITUDE).commit(); //SECURITY HAZARD: read below...
Then you can retrieve it like this:
String username = p.getString("Lat", "");
String password = p.getString("Long", "");
Hope it will help you.
make a method like this and just pass values as parameter.
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
you can put long in it. change it to this
private void SavePreferences(String key, long value)
editor.putInt(key,value)

I was not able to display the marker(pushpin.gif) on a google map - Android application using Eclipse

I copied a pushpin.gif to the appropriate folder: project/res/drawable-mdpi/pushpin.gif
I am not able to display the marker on the map, here is the code i used:
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.GeoPoint;
import android.view.KeyEvent;
import com.google.android.maps.MapController;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import com.google.android.maps.Overlay;
import java.util.List;
import android.view.MotionEvent;
import android.widget.Toast;
import android.location.Address;
import android.location.Geocoder;
import java.util.Locale;
import java.io.IOException;
public class MainActivity extends MapActivity {
MapView mapView;
MapController mc;
GeoPoint p;
class MapOverlay extends com.google.android.maps.Overlay
{
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when)
{
super.draw(canvas, mapView, shadow);
//---translate the GeoPoint to screen pixels---
Point screenPts = new Point();
mapView.getProjection().toPixels(p, screenPts);
//---add the marker---
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.pushpin);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);
return true;
}
#Override
public boolean onTouchEvent(MotionEvent event, MapView mapView)
{
//---when user lifts his finger---
if (event.getAction() == 1) {
GeoPoint p = mapView.getProjection().fromPixels(
(int) event.getX(),
(int) event.getY());
/* --To display the lat & long on the screen--
Toast.makeText(getBaseContext(), "Location: "+ p.getLatitudeE6() / 1E6 + "," + p.getLongitudeE6() /1E6 ,Toast.LENGTH_SHORT).show();*/
/*Geo Locating the empire state
Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocationName("empire state building", 5);
String add = "";
if (addresses.size() > 0) {
p = new GeoPoint(
(int) (addresses.get(0).getLatitude() * 1E6),
(int) (addresses.get(0).getLongitude() * 1E6));
mc.animateTo(p);
mapView.invalidate();
}
} catch (IOException e) {
e.printStackTrace();
}*/
Geocoder geoCoder = new Geocoder(
getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
p.getLatitudeE6() / 1E6,
p.getLongitudeE6() / 1E6, 1);
String add = "";
if (addresses.size() > 0)
{
for (int i=0; i<addresses.get(0).getMaxAddressLineIndex(); i++)
add += addresses.get(0).getAddressLine(i) + "\n";
}
Toast.makeText(getBaseContext(), add, Toast.LENGTH_SHORT).show();
}
catch (IOException e) {
e.printStackTrace();
}
return true;
}
return false;
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//To display the built-in zoom controls
mapView = (MapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
/*
//To change the view to Satellite
mapView.setSatellite(true);
*/
/*
//To change the view to Street
mapView.setStreetView(true);
*/
//assign the mapview to MapController object"oc"
mc = mapView.getController();
//the coordinates in micro degrees
String coordinates[] = {"33.717261","-117.763589"};
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);
//Gep point to represent geographical location
p = new GeoPoint(
//the coordinates in micro degrees
(int) (lat * 1E6),
(int) (lng * 1E6));
//To navigate the map to a particular location
mc.animateTo(p);
//To Specify the zoom level
mc.setZoom(13);
//Add a location marker
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
//Method to force the MapView to be redrawn
mapView.invalidate();
//To display traffic conditions on the Map
// mapView.setTraffic(true);
}
public boolean onKeyDown(int keyCode, KeyEvent event)
{
MapController mc = mapView.getController();
switch (keyCode)
{
case KeyEvent.KEYCODE_3:
mc.zoomIn();
break;
case KeyEvent.KEYCODE_1:
mc.zoomOut();
break;
}
return super.onKeyDown(keyCode, event);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
I was able to find a sample project that explains all the issues I faced.
https://github.com/commonsguy/cw-android/tree/master/Maps/NooYawk/
class MyMapOverlays extends com.google.android.maps.Overlay
{
GeoPoint location = null;
public MyMapOverlays(GeoPoint location)
{
super();
this.location = location;
}
#Override
public void draw(Canvas canvas, MapView mapView, boolean shadow)
{
super.draw(canvas, mapView, shadow);
//translate the screen pixels
Point screenPoint = new Point();
mapView.getProjection().toPixels(this.location, screenPoint);
//add the image
canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.our_cross_image),
screenPoint.x, screenPoint.y , null); //Setting the image location on the screen (x,y).
}
}

Problem in the MapActivity

i m testing an app that uses the google maps api. My app is working but my problem is:
i want the gps to find my location and present it.If my gps in enabled,it wants some seconds to find my location.In these seconds, my app starts and uses the default long and lat..How could i add something like progress bar until my location found?thanks
this is a part of my code:
private double locationLat=37.979116;
private double locationLon=23.717766;
MapView mapView;
MapController mc;
GeoPoint p;
//..........
//in the onCreate
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER,0,0, mlocListener);
MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
// mapView.setSatellite(true);
// mapView.setStreetView(true);
mc = mapView.getController();
String lata = String.valueOf(locationLat);
String lnga = String.valueOf(locationLon);
String coordinates[] = {lata, lnga};
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);
p = new GeoPoint(
(int) (lat * 1E6),
(int) (lng * 1E6));
mc.animateTo(p);
mc.setZoom(17);
//---Add a location marker---
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
//out of onCreate
class MapOverlay extends com.google.android.maps.Overlay
{
#Override
public boolean draw(Canvas canvas, MapView mapView,
boolean shadow, long when)
{
super.draw(canvas, mapView, shadow);
//---translate the GeoPoint to screen pixels---
Point screenPts = new Point();
mapView.getProjection().toPixels(p, screenPts);
//---add the marker---
Bitmap bmp = BitmapFactory.decodeResource(
getResources(), R.drawable.avatar);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);
return true;
}
#Override
public boolean onTouchEvent(MotionEvent event, MapView mapView)
{
//---when user lifts his finger---
if (event.getAction() == 1) {
GeoPoint p = mapView.getProjection().fromPixels(
(int) event.getX(),
(int) event.getY());
Geocoder geoCoder = new Geocoder(
getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
p.getLatitudeE6() / 1E6,
p.getLongitudeE6() / 1E6, 1);
String add = "";
if (addresses.size() > 0)
{
for (int i=0; i<addresses.get(0).getMaxAddressLineIndex();
i++)
add += addresses.get(0).getAddressLine(i) + "\n";
}
Toast.makeText(getBaseContext(), add, Toast.LENGTH_SHORT).show();
}
catch (IOException e) {
e.printStackTrace();
}
return true;
}
else
return false;
}
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
//String Text = "My current location is: " +
//"Latitud = " + loc.getLatitude() +
//"Longitud = " + loc.getLongitude();
locationLat=loc.getLatitude();
locationLon=loc.getLongitude();
// Toast.makeText( getApplicationContext(),
//
// Text,
//
// Toast.LENGTH_SHORT).show();
}
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(),
"Gps Disabled",
Toast.LENGTH_SHORT ).show();
}
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(),
"Gps Enabled",
Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}/* End of Class MyLocationListener */
}/* End of Activity */
I would just put it into an ASyncTask and then pop up a Dialog Box saying finding your location...once found dismiss the dialog box...Google ASyncTask examples...that should help you out.
^^ Agreed with that not sure if you are just updating the overlay or calling your map controller to follow the lat and lon that gets updated but that is an idea you could use.
Also please read the documentation of "requestLocationUpdates" 0,0 will DESTROY a real phones battery. that is updating location every 0 milliseconds and/or 0 ft change.

Ie6*lat isnt it the same as 1000000*lat? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
package ntryn.n;
import java.util.List;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
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;
import com.google.android.maps.OverlayItem;
public class ntryn extends MapActivity
{
private MapView mapView;
private MapController mc;
GeoPoint p, p2, p3, p4;
List<Overlay> mapOverlays;
Drawable drawable, drawable2 , drawable3, drawable4;
HelloItemizedOverlay itemizedOverlay, itemizedOverlay2 , itemizedOverlay3, itemizedOverlay4;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
try{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/* Use the LocationManager class to obtain GPS locations */
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
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);
mc = mapView.getController();
mapView.setStreetView(true);
//mapView.setSatellite(true);
mc.setZoom(12);
addOverLays();
}
catch(Exception e){
Log.d("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",e.getMessage());
}
}
public void addOverLays(){
String [] coordinates = {"30.084262490272522","31.33625864982605" ,"30.084123015403748", "51.5002" , "-0.1262","31.337149143218994"};
double lat = 30.084262490272522, lat2 = 51.5002,lat3=30.084123015403748;
double log = 31.33625864982605, log2 = -0.1262,log3=31.337149143218994;
p = new GeoPoint((int) (lat * 1E6), (int) (log * 1E6));
p2 = new GeoPoint( (int) (lat2 * 1e6), (int) (log2 * 1e6));
p3=new GeoPoint( (int) (lat3 * 1000000), (int) (log3 * 1000000));
mapOverlays = mapView.getOverlays();
drawable = this.getResources().getDrawable(R.drawable.ballon);
drawable2 = this.getResources().getDrawable(R.drawable.dotred);
drawable3 = this.getResources().getDrawable(R.drawable.icon);
itemizedOverlay = new HelloItemizedOverlay(drawable,this);
itemizedOverlay2 = new HelloItemizedOverlay(drawable2,this);
itemizedOverlay3 = new HelloItemizedOverlay(drawable3,this);
OverlayItem overlayitem = new OverlayItem(p, "Cairo", " over1");
OverlayItem over2 = new OverlayItem(p2, "ulm", "over2");
OverlayItem over3 = new OverlayItem(p3, "offff", "over3");
itemizedOverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedOverlay);
itemizedOverlay2.addOverlay(over2);
mapOverlays.add(itemizedOverlay2);
itemizedOverlay2.addOverlay(over3);
mapOverlays.add(itemizedOverlay3);
mc.setZoom(17);
//mc.animateTo(p);
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
GeoPoint point = new GeoPoint( (int) (loc.getLatitude() * 1E6),
(int) (loc.getLongitude() * 1E6));
//DoubletoString(loc.getLatitude());
//DoubletoString(loc.getLongitude());
String Text = "My current location is: " +
"Latitud ="+ loc.getLatitude() +
"Longitud =" + loc.getLongitude();
Toast.makeText( getApplicationContext(),
Text,
Toast.LENGTH_SHORT).show();
mc.animateTo(point);
}
private void DoubletoString(double latitude) {
// TODO Auto-generated method stub
}
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(),
"Gps Disabled",
Toast.LENGTH_SHORT ).show();
}
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(),
"Gps Enabled",
Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
protected boolean isRouteDisplayed() {
return false;
}
}/* End of Class MyLocationListener */
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
/* End of UseGps Activity*/
it force close. this due to the 3 overlaying items when i add only 2 in other words remove the p3 which is * 1000000. it's work, but with it it doesn't zoom and when i want to zoom it show force close
1e6 is a floating point number, 1000000 is an integer.
[adrian#cheops3:~]> cat Test.java
class Test {
public static void main(String[] args) {
System.out.println("1e6 = " + 1e6);
System.out.println("1000000 = " + 1000000);
}
}
[adrian#cheops3:~]> javac Test.java && java Test
1e6 = 1000000.0
1000000 = 1000000

I want to track my current location in an Android application

Here I create one project that will track our current location.
But I have a problem coding it... I don't know exactly how to use the OVERLAY class and when it is called.
I have posted my code.. Please help me
package com.techno.gps;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
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.Projection;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.RectF;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
public class gps extends MapActivity{
MapController mapController;
Location location;
MyPositionOverlay positionOverlay;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get a reference to the MapView
MapView myMapView = (MapView)findViewById(R.id.mapView);
// Get the Map View’s controller
mapController = myMapView.getController();
// Configure the map display options
myMapView.setSatellite(true);
myMapView.setStreetView(true);
myMapView.displayZoomControls(false);
// Zoom in
mapController.setZoom(17);
//add postionoverlay
positionOverlay = new MyPositionOverlay();
List<Overlay> overlays = myMapView.getOverlays();
overlays.add(positionOverlay);
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(criteria, true);
location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider, 2000, 10,locationListener);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
private void updateWithNewLocation(Location location)
{
String latLongString;
TextView myLocationText;
myLocationText = (TextView)findViewById(R.id.myLocationText);
String addressString = "No address found";
if (location != null) {
// Update the map location.
positionOverlay.setLocation(location);
Double geoLat = location.getLatitude()*1E6;
Double geoLng = location.getLongitude()*1E6;
GeoPoint point = new GeoPoint(geoLat.intValue(),
geoLng.intValue());
mapController.animateTo(point);
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "Lat: "+ lat + " Long:" + lng;
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Geocoder gc = new Geocoder(this, Locale.getDefault());
try
{
List<Address> addresses = gc.getFromLocation(latitude, longitude, 1);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0)
{
Address address = addresses.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
{
sb.append(address.getAddressLine(i)).append("\n");
}
sb.append(address.getLocality()).append("\n");
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
}
addressString = sb.toString();
}
catch (IOException e)
{
}
}
else
{
latLongString = "No location found";
}
myLocationText.setText("Your Current Position is:\n" +latLongString + "\n" + addressString);
}
private final LocationListener locationListener = new LocationListener()
{
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider)
{
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider)
{
}
public void onStatusChanged(String provider, int status,Bundle extras)
{
}
};
public class MyPositionOverlay extends Overlay
{
Location location;
#Override
public void draw(Canvas canvas, MapView mapView, boolean shadow)
{
Projection projection = mapView.getProjection();
if (shadow == false) {
// Get the current location
Double latitude = location.getLatitude()*1E6;
Double longitude = location.getLongitude()*1E6;
GeoPoint geoPoint;
geoPoint = new GeoPoint(latitude.intValue(),longitude.intValue());
// Convert the location to screen pixels
int mRadius=5;
Point point = new Point();
projection.toPixels(geoPoint, point);
RectF oval = new RectF(point.x - mRadius, point.y - mRadius,
point.x + mRadius, point.y + mRadius);
// Setup the paint
Paint paint = new Paint();
paint.setARGB(250, 255, 0, 0);
paint.setAntiAlias(true);
paint.setFakeBoldText(true);
Paint backPaint = new Paint();
backPaint.setARGB(175, 50, 50, 50);
backPaint.setAntiAlias(true);
RectF backRect = new RectF(point.x + 2 + mRadius,
point.y - 3*mRadius,
point.x + 65, point.y + mRadius);
// Draw the marker
canvas.drawOval(oval, paint);
canvas.drawRoundRect(backRect, 5, 5, backPaint);
canvas.drawText("Here I Am", point.x + 2*mRadius, point.y, paint);
}
super.draw(canvas, mapView, shadow);
}
#Override
public boolean onTap(GeoPoint point, MapView mapView)
{
// Return true if screen tap is handled by this overlay
return false;
}
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
}
}
thanks...
Strange that you don't know your own code. You should try writing it by yourself. Copy-pasting does not work always.
To answer your question. An Overlay is drawable object that can be shown on top of the map on a different layer above the MapView.
This is the part of the code where you add that drawing to the MapView.
positionOverlay = new MyPositionOverlay();
List<Overlay> overlays = myMapView.getOverlays();
overlays.add(positionOverlay);
You are doing this in OnCreate(). Which does not makes sense, because you have no position fix yet.
Add the overlay when you get a pos-fix in updateWithNewLocation()
To call draw forcefully use MapView.invalidate()
i have the same example code, with 2.2 android, works, but don't drow the overlay, with my position, otherwise, with debuggin you can see code working properltly. Really strange.
I think code is correct, because, in onCreate, code is initializated, then in updateWithNewLocation, the overlay is updated with positionOverlay.setLocation(location);

Categories

Resources