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)
Related
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).
}
}
Hi I'm using the code from below link to draw route between two points in map.
http://code.google.com/p/j2memaprouteprovider/source/browse/#svn/trunk/J2MEMapRouteAndroidEx/src/org/ci/geo/route
Also I'm using timer to update locations dynamically every 30 seconds. It works good. But the application freezes after 20 seconds. After the route is drawn between 2 points app becomes slow while zooming in or zooming out the map.
Is there any other efficient way to draw route between 2 points or in Async task??
Any help Appreciated.
Refer this LINK
SharedData.java
package com.agarwal.route;
public class SharedData {
// this is a singleton class that provides a global data share for all of the
// activities and services in the MDWrapper application
private static SharedData instance = null;
private SharedData() {
//randomizeServers();
}
// data to be shared
private String APIKEY = "";
private double src_lat = -1;
private double src_lng = -1;
private double dest_lat = -1;
private double dest_lng = -1;
/**
* #return the aPIKEY
*/
public String getAPIKEY() {
return APIKEY;
}
/**
* #param aPIKEY the aPIKEY to set
*/
public void setAPIKEY(String aPIKEY) {
APIKEY = aPIKEY;
}
/**
* #return the src_lat
*/
public double getSrc_lat() {
return src_lat;
}
/**
* #param src_lat the src_lat to set
*/
public void setSrc_lat(double src_lat) {
this.src_lat = src_lat;
}
/**
* #return the src_lng
*/
public double getSrc_lng() {
return src_lng;
}
/**
* #param src_lng the src_lng to set
*/
public void setSrc_lng(double src_lng) {
this.src_lng = src_lng;
}
/**
* #return the dest_lat
*/
public double getDest_lat() {
return dest_lat;
}
/**
* #param dest_lat the dest_lat to set
*/
public void setDest_lat(double dest_lat) {
this.dest_lat = dest_lat;
}
/**
* #return the dest_lng
*/
public double getDest_lng() {
return dest_lng;
}
/**
* #param dest_lng the dest_lng to set
*/
public void setDest_lng(double dest_lng) {
this.dest_lng = dest_lng;
}
public static SharedData getInstance() {
if (null == instance) {
instance = new SharedData();
}
return instance;
}
}
CustomItemizedOverlay.java
package com.agarwal.route;
import java.util.ArrayList;
import android.graphics.drawable.Drawable;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;
public class CustomItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private final ArrayList<OverlayItem> mapOverlays = new ArrayList<OverlayItem>();
public CustomItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
#Override
protected OverlayItem createItem(int i) {
return mapOverlays.get(i);
}
#Override
public int size() {
return mapOverlays.size();
}
public void addOverlay(OverlayItem overlay) {
mapOverlays.add(overlay);
this.populate();
}
}
MyOverLay.java
package com.agarwal.route;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;
public class MyOverLay extends Overlay
{
private GeoPoint gp1;
private GeoPoint gp2;
private int mode=0;
private int defaultColor;
Context mContext;
public MyOverLay(Context context,GeoPoint gp1,GeoPoint gp2,int mode) // GeoPoint is a int. (6E)
{
this.gp1 = gp1;
this.gp2 = gp2;
this.mode = mode;
this.mContext = context;
defaultColor = 999; // no defaultColor
}
public MyOverLay(GeoPoint gp1,GeoPoint gp2,int mode, int defaultColor)
{
this.gp1 = gp1;
this.gp2 = gp2;
this.mode = mode;
this.defaultColor = defaultColor;
}
public int getMode()
{
return mode;
}
#Override
public boolean draw
(Canvas canvas, MapView mapView, boolean shadow, long when)
{
Projection projection = mapView.getProjection();
if (shadow == false)
{
Paint paint = new Paint();
paint.setAntiAlias(true);
Point point = new Point();
projection.toPixels(gp1, point);
// mode=1:start
if(mode==1)
{
if(defaultColor==999)
paint.setColor(Color.BLUE);
else
paint.setColor(defaultColor);
// start point
}
// mode=2:path
else if(mode==2)
{
if(defaultColor==999)
paint.setColor(Color.RED);
else
paint.setColor(defaultColor);
Point point2 = new Point();
projection.toPixels(gp2, point2);
paint.setStrokeWidth(5);
paint.setAlpha(120);
canvas.drawLine(point.x, point.y, point2.x,point2.y, paint);
}
/* mode=3:end */
else if(mode==3)
{
/* the last path */
if(defaultColor==999)
paint.setColor(Color.GREEN);
else
paint.setColor(defaultColor);
Point point2 = new Point();
projection.toPixels(gp2, point2);
paint.setStrokeWidth(5);
paint.setAlpha(120);
canvas.drawLine(point.x, point.y, point2.x,point2.y, paint);
/* end point */
}
}
return super.draw(canvas, mapView, shadow, when);
}
}
RoutePath.java
package com.agarwal.route;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
public class RoutePath extends MapActivity {
/** Called when the activity is first created. */
MapView mapView;
private RoutePath _activity;
GeoPoint srcGeoPoint,destGeoPoint;
private static List<Overlay> mOverlays;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedData data = SharedData.getInstance();
mapView = new MapView(this,data.getAPIKEY());
mapView.setClickable(true);
setContentView(mapView);
_activity = this;
double src_lat = data.getSrc_lat();
double src_long = data.getSrc_lng();
double dest_lat = data.getDest_lat();
double dest_long = data.getDest_lng();
if(src_lat == -1 || src_long == -1 || dest_lat == -1 || dest_long == -1){
showAlert("Please enter source and destination points");
}else{
srcGeoPoint = new GeoPoint((int) (src_lat * 1E6),(int) (src_long * 1E6));
destGeoPoint = new GeoPoint((int) (dest_lat * 1E6),(int) (dest_long * 1E6));
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable srcdrawable = this.getResources().getDrawable(R.drawable.pin_green);
//CustomItemizedOverlay srcitemizedOverlay = new CustomItemizedOverlay(getDrawable("com/agarwal/route/pin_green.png"));
OverlayItem srcoverlayitem = new OverlayItem(srcGeoPoint, "Hello!", "This is your Location.");
Drawable destdrawable = this.getResources().getDrawable(R.drawable.pin_red);
// CustomItemizedOverlay destitemizedOverlay = new CustomItemizedOverlay(getDrawable("com/agarwal/route/pin_red.png"));
OverlayItem destoverlayitem = new OverlayItem(destGeoPoint, "Hello!", "This is dest Location.");
srcitemizedOverlay.addOverlay(srcoverlayitem);
destitemizedOverlay.addOverlay(destoverlayitem);
mapOverlays.add(srcitemizedOverlay);
mapOverlays.add(destitemizedOverlay);
connectAsyncTask _connectAsyncTask = new connectAsyncTask();
_connectAsyncTask.execute();
mapView.setBuiltInZoomControls(true);
mapView.displayZoomControls(true);
mOverlays = mapView.getOverlays();
mapView.getController().animateTo(srcGeoPoint);
mapView.getController().setZoom(12);
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
private class connectAsyncTask extends AsyncTask<Void, Void, Void>{
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = new ProgressDialog(_activity);
progressDialog.setMessage("Fetching route, Please wait...");
progressDialog.setIndeterminate(true);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
fetchData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(doc!=null){
Overlay ol = new MyOverLay(_activity,srcGeoPoint,srcGeoPoint,1);
mOverlays.add(ol);
NodeList _nodelist = doc.getElementsByTagName("status");
Node node1 = _nodelist.item(0);
String _status1 = node1.getChildNodes().item(0).getNodeValue();
if(_status1.equalsIgnoreCase("OK")){
NodeList _nodelist_path = doc.getElementsByTagName("overview_polyline");
Node node_path = _nodelist_path.item(0);
Element _status_path = (Element)node_path;
NodeList _nodelist_destination_path = _status_path.getElementsByTagName("points");
Node _nodelist_dest = _nodelist_destination_path.item(0);
String _path = _nodelist_dest.getChildNodes().item(0).getNodeValue();
List<GeoPoint> _geopoints = decodePoly(_path);
GeoPoint gp1;
GeoPoint gp2;
gp2 = _geopoints.get(0);
Log.d("_geopoints","::"+_geopoints.size());
for(int i=1;i<_geopoints.size();i++) // the last one would be crash
{
gp1 = gp2;
gp2 = _geopoints.get(i);
Overlay ol1 = new MyOverLay(gp1,gp2,2,Color.BLUE);
mOverlays.add(ol1);
}
Overlay ol2 = new MyOverLay(_activity,destGeoPoint,destGeoPoint,3);
mOverlays.add(ol2);
progressDialog.dismiss();
}else{
showAlert("Unable to find the route");
}
Overlay ol2 = new MyOverLay(_activity,destGeoPoint,destGeoPoint,3);
mOverlays.add(ol2);
progressDialog.dismiss();
mapView.scrollBy(-1,-1);
mapView.scrollBy(1,1);
}else{
showAlert("Unable to find the route");
}
}
}
Document doc = null;
private void fetchData()
{
StringBuilder urlString = new StringBuilder();
urlString.append("http://maps.google.com/maps/api/directions/xml?origin=");
urlString.append( Double.toString((double)srcGeoPoint.getLatitudeE6()/1.0E6 ));
urlString.append(",");
urlString.append( Double.toString((double)srcGeoPoint.getLongitudeE6()/1.0E6 ));
urlString.append("&destination=");//to
urlString.append( Double.toString((double)destGeoPoint.getLatitudeE6()/1.0E6 ));
urlString.append(",");
urlString.append( Double.toString((double)destGeoPoint.getLongitudeE6()/1.0E6 ));
urlString.append("&sensor=true&mode=driving");
Log.d("url","::"+urlString.toString());
HttpURLConnection urlConnection= null;
URL url = null;
try
{
url = new URL(urlString.toString());
urlConnection=(HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = (Document) db.parse(urlConnection.getInputStream());//Util.XMLfromString(response);
}catch (MalformedURLException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}catch (ParserConfigurationException e){
e.printStackTrace();
}
catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private List<GeoPoint> decodePoly(String encoded) {
List<GeoPoint> poly = new ArrayList<GeoPoint>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
GeoPoint p = new GeoPoint((int) (((double) lat / 1E5) * 1E6),
(int) (((double) lng / 1E5) * 1E6));
poly.add(p);
}
return poly;
}
private void showAlert(String message){
AlertDialog.Builder alert = new AlertDialog.Builder(_activity);
alert.setTitle("Error");
alert.setCancelable(false);
alert.setMessage(message);
alert.setPositiveButton("Ok",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
alert.show();
}
private Drawable getDrawable(String fileName){
return Drawable.createFromStream(_activity.getClass().getClassLoader().getResourceAsStream(fileName), "pin");
}
}
In Your Activity Just Paste the below few lines to draw routemap:
SharedData data = SharedData.getInstance();
data.setAPIKEY("0RUTLH7cqd6yrZ0FdS0NfQMO3lioiCbnH-BpNQQ");
data.setSrc_lat(17);
data.setSrc_lng(78);
data.setDest_lat(18);
data.setDest_lng(77);
startActivity(new Intent(YourActivity.this,RoutePath.class));
Note:: Need to RoutePath activity and permssions in your manifeast file
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);
}
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
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);