I am using OSMdroid.
I have managed thanks to this post Adding Overlay to OSMDROID to creata overlay static item on a specific location.
now I am trying to make the map little bit more dynamic. so when the location change the OverLayItem (which marking the specific location on the map) will update itself also.
this is what I tried to do. the map does update but the OverLayItem doesnt.
code:
package com.test.overlay;
import java.util.ArrayList;
import org.osmdroid.DefaultResourceProxyImpl;
import org.osmdroid.ResourceProxy;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapController;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.ItemizedIconOverlay;
import org.osmdroid.views.overlay.ItemizedOverlay;
import org.osmdroid.views.overlay.OverlayItem;
import org.osmdroid.views.util.constants.MapViewConstants;
import android.app.Activity;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;
public class SampleWithMinimapItemizedoverlay extends Activity implements
LocationListener, MapViewConstants
{
private MapView mMapView;
private MapController mapController;
private LocationManager mLocMgr;
private ItemizedOverlay<OverlayItem> mMyLocationOverlay;
private ResourceProxy mResourceProxy;
int longtitude = 31987968;
int latitude = 34783155;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mResourceProxy = new DefaultResourceProxyImpl(getApplicationContext());
setContentView(R.layout.main);
mMapView = (MapView) this.findViewById(R.id.mapview);
mMapView.setTileSource(TileSourceFactory.MAPNIK);
mMapView.setBuiltInZoomControls(true);
mMapView.setMultiTouchControls(true);
mapController = this.mMapView.getController();
mapController.setZoom(15);
GeoPoint point2 = new GeoPoint(longtitude, latitude); // centre map here
GeoPoint point3 = new GeoPoint(longtitude + 2000, latitude + 2000); // icon
// goes
// here
// 31.987968,34.783155
mapController.setCenter(point2);
mLocMgr = (LocationManager) getSystemService(LOCATION_SERVICE);
mLocMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 100,
this);
ArrayList<OverlayItem> items = new ArrayList<OverlayItem>();
// Put overlay icon a little way from map centre
items.add(new OverlayItem("Here", "SampleDescription", point3));
/* OnTapListener for the Markers, shows a simple Toast. */
this.mMyLocationOverlay = new ItemizedIconOverlay<OverlayItem>(items,
new ItemizedIconOverlay.OnItemGestureListener<OverlayItem>()
{
#Override
public boolean onItemSingleTapUp(final int index,
final OverlayItem item)
{
Toast.makeText(SampleWithMinimapItemizedoverlay.this,
"Item '" + item.mTitle, Toast.LENGTH_LONG)
.show();
return true; // We 'handled' this event.
}
#Override
public boolean onItemLongPress(final int index,
final OverlayItem item)
{
Toast.makeText(SampleWithMinimapItemizedoverlay.this,
"Item '" + item.mTitle, Toast.LENGTH_LONG)
.show();
return false;
}
}, mResourceProxy);
this.mMapView.getOverlays().add(this.mMyLocationOverlay);
mMapView.invalidate();
}
-------//here I tried to do the change !!!!!!!!!---------------
-- The map location being updated but not the overlayItem.
public void onLocationChanged(Location location)
{
latitude = (int) (location.getLatitude() * 1E6);
longtitude = (int) (location.getLongitude() * 1E6);
Toast.makeText(SampleWithMinimapItemizedoverlay.this,
"Location changed. Lat:" + latitude + " long:" + longtitude ,
Toast.LENGTH_LONG).show();
GeoPoint gpt = new GeoPoint(latitude, longtitude);
mapController.setCenter(gpt);
mMapView.invalidate();
}
#Override
public void onProviderDisabled(String arg0)
{
}
#Override
public void onProviderEnabled(String provider)
{
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
Thanks,
ray.
This should work OK
.
public class SampleWithMinimapItemizedoverlay extends Activity implements
LocationListener, MapViewConstants {
private MapView mMapView;
private MapController mapController;
private LocationManager mLocMgr;
private ItemizedOverlay<OverlayItem> mMyLocationOverlay;
private ResourceProxy mResourceProxy;
int mLongtitude = 31987968;
int mLatitude = 34783155;
ArrayList<OverlayItem> mItems;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mResourceProxy = new DefaultResourceProxyImpl(getApplicationContext());
setContentView(R.layout.main);
mMapView = (MapView) this.findViewById(R.id.mapview);
mMapView.setTileSource(TileSourceFactory.MAPNIK);
mMapView.setBuiltInZoomControls(true);
mMapView.setMultiTouchControls(true);
mapController = this.mMapView.getController();
mapController.setZoom(15);
GeoPoint point2 = new GeoPoint(mLongtitude, mLatitude); // centre map here
GeoPoint point3 = new GeoPoint(mLongtitude + 2000, mLatitude + 2000); // icon
// goes
// 31.987968,34.783155
mapController.setCenter(point2);
mLocMgr = (LocationManager) getSystemService(LOCATION_SERVICE);
mLocMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 100,
this);
mItems = new ArrayList<OverlayItem>();
// Put overlay icon a little way from map centre
mItems.add(new OverlayItem("Here", "SampleDescription", point3));
/* OnTapListener for the Markers, shows a simple Toast. */
// REFER TO THE GESTURE LISTEMER BY NAME NOW
this.mMyLocationOverlay = new ItemizedIconOverlay<OverlayItem>(mItems,
new Glistener() , mResourceProxy);
this.mMapView.getOverlays().add(this.mMyLocationOverlay);
mMapView.invalidate();
}
//We can't use an anonymous class anymore if we want to change the position
// of the overlays/icons when location changed, give it a name
class Glistener implements OnItemGestureListener<OverlayItem> {
#Override
public boolean onItemLongPress(int index, OverlayItem item) {
Toast.makeText(SampleWithMinimapItemizedoverlay.this, "Item " + item.mTitle,
Toast.LENGTH_LONG).show();
return false;
}
#Override
public boolean onItemSingleTapUp(int index, OverlayItem item) {
Toast.makeText(SampleWithMinimapItemizedoverlay.this, "Item " + item.mTitle,
Toast.LENGTH_LONG).show();
return true; // We 'handled' this event.
}
}
// -------//here I tried to do the change !!!!!!!!!---------------
// -- The map location being updated but not the overlayItem.
public void onLocationChanged(Location location) {
mLatitude = (int) (location.getLatitude() * 1E6);
mLongtitude = (int) (location.getLongitude() * 1E6);
Toast.makeText(SampleWithMinimapItemizedoverlay.this,
"Location changed. Lat:" + mLatitude + " long:" + mLongtitude,
Toast.LENGTH_LONG).show();
GeoPoint gpt = new GeoPoint(mLatitude, mLongtitude);
mapController.setCenter(gpt);
mItems.clear(); // COMMENT OUT THIS LINE IF YOU WANT A NEW ICON FOR EACH CHANGE OF POSITION
mItems.add(new OverlayItem("New", "SampleDescription", gpt));
// Change the overlay
this.mMyLocationOverlay = new ItemizedIconOverlay<OverlayItem>(mItems,
new Glistener() , mResourceProxy);
this.mMapView.getOverlays().clear();
this.mMapView.getOverlays().add(this.mMyLocationOverlay);
mMapView.invalidate();
}
#Override
public void onProviderDisabled(String arg0) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
Just comment/uncomment the mItems.clear(); line depending on whether you want a new marker each time you change position. (The icon appears atthe position that you have moved to)
Related
I am Trying to develop small application in which i am trying to Detect Location.
I am using the following code but i don't know why my application crashes. It show the application stops Unfortunately.
Here is the code. Please tell me if there is any bug and if not then please at least reply.
Thanks.
Here is the Code.
package com.project.kamani.nearby;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
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.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class Map extends Activity implements LocationListener{
public GoogleMap google_map;
public List<Address> addresses;
public Geocoder geocoder;
private Location location;
private double lat;
private double lang;
private Criteria criteria;
private LocationManager location_manager;
private String provider;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES=20;//DISTANCE IN METERS
private static final long MIN_TIME_BW_UPDATES=1000*60*1;// TAKES UPDATE AFTER 1 MINUTES
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(isGooglePlayAvailable())
{
criteria=new Criteria();
setContentView(R.layout.mapdemo);
getGoogleMap();
getUserLocation();
//Toast.makeText(this, "Latitude:"+lat+" Longitude:"+lang, Toast.LENGTH_LONG).show();
getAddress(lat,lang);
drawMarker(lat,lang);
}
}
private boolean isGooglePlayAvailable(){
int status=GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if(status==ConnectionResult.SUCCESS)
return true;
else
GooglePlayServicesUtil.getErrorDialog(status, this, 10).show();
return false;
}
private void getGoogleMap(){
if(google_map==null){
google_map=((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
}
}
private void drawMarker(double lattitude,double longitude){
google_map.clear();
google_map.setMyLocationEnabled(true);
LatLng latlng=new LatLng(lattitude, longitude);
google_map.moveCamera(CameraUpdateFactory.newLatLng(latlng));
google_map.animateCamera(CameraUpdateFactory.zoomTo(15));
LatLng currentPosition = new LatLng(lattitude,longitude);
google_map.addMarker(new MarkerOptions().position(currentPosition).snippet("Address:" + addresses.get(0).getAddressLine(0) + "City:"+ addresses.get(0).getAddressLine(1)+"Country:"+addresses.get(0).getAddressLine(2)).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)).title("ME"));
}
private void getAddress(double lattitude,double longitude){
geocoder=new Geocoder(Map.this, Locale.getDefault());
try {
addresses=geocoder.getFromLocation(lattitude, longitude, 1);
Toast.makeText(Map.this, "Address:" + addresses.get(0).getAddressLine(0) + "City:"+ addresses.get(0).getAddressLine(1)+"Country:"+addresses.get(0).getAddressLine(2), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
private void getUserLocation(){
location_manager=(LocationManager) getSystemService(LOCATION_SERVICE);
if(location_manager!=null){
provider=location_manager.getBestProvider(criteria, true);
location=location_manager.getLastKnownLocation(provider);
location_manager.requestLocationUpdates(provider, Map.MIN_TIME_BW_UPDATES, Map.MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
lat=location.getLatitude();
lang=location.getLongitude();
}
}
#Override
public void onLocationChanged(Location location) {
google_map.clear();
drawMarker(lat, lang);
}
#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
}
}
Here is the snapshot that error i am getting in logcat.
I hope it will be helpful to solve error.
EDIT:-
If you don't want to monitor once again full code just try to view at getUserLocation method still the application stops working when i enable the GPS thanks for your support.
location is never initialized. Your are setting location as the variable that will hold the return value of getUserLocation() and it is also its parameter; both are null.
public class MainActivity extends MapActivity implements LocationListener {
private MapView mapView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 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 = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// 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 onLocationChanged(Location location) {
TextView tvLocation = (TextView) findViewById(R.id.tv_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);
}
#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
}
}
Download Here
I have been using a previous question and a Google Tutorial to attempt to add multiple pin images on a Google Map view when the current location of the user changes.
Each pin when tapped displays the Longitude and Latitude of the pin.
However currently my code only displays one pin and does not add another image when the location of the user changes. I am relatively new to Android and can't see why this code wouldn't work?
Map.java:
import java.util.List;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
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.MyLocationOverlay;
import com.google.android.maps.OverlayItem;
import android.util.Log;
public class Map extends MapActivity {
private MapView map;
private MapController controller;
private double lon, lat;
private Drawable drawable;
private MapOverlay itemizedoverlay;
private List<Overlay> mapOverlays;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps);
initMapView();
mapOverlays = map.getOverlays();
drawable = this.getResources().getDrawable(R.drawable.pin);
itemizedoverlay = new MapOverlay(drawable, this);
initMyLocation();
}
private void initMapView() {
map = (MapView) findViewById(R.id.map);
controller = map.getController();
map.setSatellite(true);
map.setBuiltInZoomControls(true);
}
private void initMyLocation() {
final MyLocationOverlay overlay = new MyLocationOverlay(this, map);
overlay.enableMyLocation();
overlay.enableCompass(); // wont work in emulator
overlay.runOnFirstFix(new Runnable() {
public void run() {
// Zoom in to current location - 1 is word view
controller.setZoom(20);
controller.animateTo(overlay.getMyLocation());
lon = overlay.getMyLocation().getLongitudeE6();
lat = overlay.getMyLocation().getLatitudeE6();
setLON(lon);
setLAT(lat);
//-0.959896
//51.742953
Log.w("test-lon", Double.toString(lon/1E6));
Log.w("test-lat", Double.toString(lat/1E6));
GeoPoint point = new GeoPoint((int)(lat),(int)(lon));
mapOverlays.add(itemizedoverlay);
test(point);
}
});
map.getOverlays().add(overlay);
}
public void setLON(double x){ //remove?
lon = x;
}
public void setLAT(double x){ //remove?
lat = x;
}
public void test(GeoPoint px){
OverlayItem overlayitem = new OverlayItem(px,"Test Point" , "Lat: " + Double.toString(lat/1E6) + "\nLon: " + Double.toString(lon/1E6) );
itemizedoverlay.addOverlay(overlayitem);
}
#Override
protected boolean isRouteDisplayed() {
// Required method from MapActivity
return false;
}
}
MapOverlay.java:
import java.util.ArrayList;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;
public class MapOverlay extends ItemizedOverlay {
private ArrayList<OverlayItem> mapOverlay = new ArrayList<OverlayItem>();
private Context mContext;
public MapOverlay (Drawable defaultMarker, Context context) {
super(boundCenterBottom(defaultMarker));
mContext = context;
}
public MapOverlay(Drawable arg0) {
super(boundCenterBottom(arg0));
}
public void addOverlay(OverlayItem overlay) {
mapOverlay.add(overlay);
populate();
}
#Override
protected OverlayItem createItem(int i) {
return mapOverlay.get(i);
}
#Override
public int size() {
return mapOverlay.size();
}
#Override
protected boolean onTap(int index) {
OverlayItem item = mapOverlay.get(index);
AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.show();
return true;
}
}
u need implements class LocationListener for listen our location changes and update on the map.
class LocationsListeners implements LocationListener {
#Override
public void onLocationChanged(Location location) {
setLAT(location.getLatitude());
setLON(location.getLongitude());
setGeoPoint(lat, lon);
mapOverlays.add(geoPoint);
}
#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
}
}
u need method for calc the GeoPoint:
public GeoPoint setGeoPoint(double lat, double lon){
geoPoint = new GeoPoint((int) (lat * 1E6), (int)(lon * 1E6));
return geoPoint;
}
or using Little Fluffy Location - Its library that updates our location and notify u, is broadcast receiver, very simple and fast implementation:
try:
http://code.google.com/p/little-fluffy-location-library/
I searched for two hours but only found draw Line, i want get direction as this form Click here! I have ten point and when i click the point i want to show direction from my location to the point.
My code look:
package de.vogella.android.locationapi.maps;
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 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.MyLocationOverlay;
import com.google.android.maps.OverlayItem;
import com.google.android.maps.Projection;
public class ShowMapActivity extends MapActivity {
private MapController mapController;
private MapView mapView;
private LocationManager locationManager;
private MyOverlays itemizedoverlay,itemizedoverlay_central;
private MyLocationOverlay myLocationOverlay;
private String nameOfOffice_AZ[];
private String addressOfOffice_AZ[];
private String phoneOfOffice_AZ[];
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.main); // bind the layout to the activity
// Configure the Map
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
Projection projection = mapView.getProjection();
nameOfOffice_AZ= getResources().getStringArray(R.array.NamesOFObject_AZ);
addressOfOffice_AZ = getResources().getStringArray(R.array.AddressOfOffice_AZ);
phoneOfOffice_AZ = getResources().getStringArray(R.array.PhoneOfOffice_AZ);
mapController = mapView.getController();
mapController.setZoom(16); // Zoon 1 is world view
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, new GeoUpdateHandler());
myLocationOverlay = new MyLocationOverlay(this, mapView);
mapView.getOverlays().add(myLocationOverlay);
myLocationOverlay.runOnFirstFix(new Runnable() {
public void run() {
mapView.getController().animateTo(myLocationOverlay.getMyLocation());
}
});
Drawable drawable = this.getResources().getDrawable(R.drawable.office_icon);
Drawable drawable_central = this.getResources().getDrawable(R.drawable.central_office);
itemizedoverlay = new MyOverlays(this, drawable);
itemizedoverlay_central = new MyOverlays(this, drawable_central);
createMarker();
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
public class GeoUpdateHandler implements LocationListener {
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude() * 1E6);
int lng = (int) (location.getLongitude() * 1E6);
GeoPoint point = new GeoPoint(lat, lng);
createMarker();
mapController.animateTo(point); // mapController.setCenter(point);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
private void createMarker() {
//CENTRAL OFFICE
GeoPoint p_central = new GeoPoint((int)(40.38292884084829 * 1e6),(int)(49.84223246574 * 1e6));
OverlayItem overlayitem = new OverlayItem(p_central, nameOfOffice_AZ[0] ,addressOfOffice_AZ[0]+"\n"+phoneOfOffice_AZ[0] );
itemizedoverlay_central.addOverlay(overlayitem);
mapView.getOverlays().add(itemizedoverlay_central);
//END CENTRALL OFFICE
GeoPoint p = new GeoPoint((int)(40.376455916943236 * 1e6),(int)(49.84803676605224 * 1e6));
overlayitem = new OverlayItem(p, nameOfOffice_AZ[0] ,addressOfOffice_AZ[0]+"\n"+phoneOfOffice_AZ[0] );
itemizedoverlay.addOverlay(overlayitem);
mapView.getOverlays().add(itemizedoverlay);
}
#Override
protected void onResume() {
super.onResume();
myLocationOverlay.enableMyLocation();
myLocationOverlay.enableCompass();
}
#Override
protected void onPause() {
super.onPause();
myLocationOverlay.disableMyLocation();
myLocationOverlay.disableCompass();
}
}
and MyOverlays.java
package de.vogella.android.locationapi.maps;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;
public class MyOverlays extends ItemizedOverlay<OverlayItem> {
private static int maxNum = 5;
private OverlayItem overlays[] = new OverlayItem[maxNum];
private int index = 0;
private boolean full = false;
private Context mContext;
private OverlayItem previousoverlay;
public MyOverlays(Context context, Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
this.mContext = context;
}
private ArrayList< OverlayItem > mOverlays = new ArrayList< OverlayItem >();
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
populate();
}
public void name() {
}
#Override
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
#Override
public int size() {
return mOverlays.size();
}
#Override
protected boolean onTap(int i) {
//when you tap on the marker this will show the informations provided by you when you create in the
//main class the OverlayItem
OverlayItem item = mOverlays.get(i);
AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
dialog.setInverseBackgroundForced(true);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.setCancelable(true);
dialog.setPositiveButton("Go To", new OkOnClickListener());
/// dialog.setNegativeButton("No, no", new CancelOnClickListener());
dialog.show();
// nese bax = new nese();
// bax.oldu(mContext);
return true;
}
private final class CancelOnClickListener implements
DialogInterface.OnClickListener {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(mContext, "You clicked yes", Toast.LENGTH_LONG)
.show();
}
}
private final class OkOnClickListener implements
DialogInterface.OnClickListener {
public void onClick(DialogInterface dialog, int which) {
//Toast.makeText(mContext, "You clicked no", Toast.LENGTH_LONG).show();
}
}
public class RoutePath extends MapActivity {
/** Called when the activity is first created. */
MapView mapView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MapView mapView = (MapView) findViewById(R.id.mapview);
double src_lat = 25.04202; // the testing source
double src_long = 121.534761;
double dest_lat = 25.05202; // the testing destination
double dest_long = 121.554761;
GeoPoint srcGeoPoint = new GeoPoint((int) (src_lat * 1E6),
(int) (src_long * 1E6));
GeoPoint destGeoPoint = new GeoPoint((int) (dest_lat * 1E6),
(int) (dest_long * 1E6));
DrawPath(srcGeoPoint, destGeoPoint, Color.GREEN, mapView);
mapView.getController().animateTo(srcGeoPoint);
mapView.getController().setZoom(15);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
private void DrawPath(GeoPoint src, GeoPoint dest, int color,
MapView mMapView01) {
// code in section 2.2
}
}
}
Less efforts on search..
Anyway look at Google Driving Directions - MapView overlayed Also The Google Directions API
and using intent
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps?saddr=xx.xx,xx.xx&daddr=xx.xx,xx.xx"));
startActivity(intent);
This blogpost can be a good startpoint: Android driving direction Route-Path
Worked fine for me.
I just wanted to know if it is possible to force a location update in order to get the position of the mobile once I click on the refresh item in the menu.
Here is the code below that I found in a forum, and I want to add a new function.
import android.os.Bundle;
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.OverlayItem;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
public class MapLocator extends MapActivity implements LocationListener {
/** Called when the activity is first created. */
private MapView mapView;
private LocationManager lm;
private MapController mc;
private double lat = 0;
private double lng = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
mapView = (MapView) this.findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mc = mapView.getController();
mc.setZoom(14);
int FIVE_MINUTES = 5 /*Minutes*/ * 60 /*sec per min*/ * 1000 /*ms per sec*/;
lm = (LocationManager) this.getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, FIVE_MINUTES, 0, this);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, FIVE_MINUTES, 0, this);
Drawable drawable= this.getResources().getDrawable(R.drawable.loc_seven);
ListItimizedOverlay itemizedoverlay = new ListItimizedOverlay(drawable);
GeoPoint p = new GeoPoint(33000000,84000000);
OverlayItem overlayitem = new OverlayItem(p, "Hello from", "Tahiti");
itemizedoverlay.addOverlayItem(overlayitem);
mapView.getOverlays().add(itemizedoverlay);
}
#Override
protected boolean isRouteDisplayed()
{
return false;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_S)
{
mapView.setSatellite(!mapView.isSatellite());
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onLocationChanged(Location location)
{
Log.d("msg","1");
lat = location.getLatitude();
lng = location.getLongitude();
Toast.makeText(
getBaseContext(),
"Location change to : Latitude = " + lat + " Longitude = "
+ lng, Toast.LENGTH_SHORT).show();
GeoPoint p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
mc.animateTo(p);
mc.setCenter(p);
mc.setZoom(14);
Drawable drawable= this.getResources().getDrawable(R.drawable.loc_seven);
ListItimizedOverlay itemizedoverlay = new ListItimizedOverlay(drawable);
OverlayItem overlayitem = new OverlayItem(p, "", "");
itemizedoverlay= (ListItimizedOverlay ) mapView.getOverlays().get(0);
itemizedoverlay.clear();
itemizedoverlay.addOverlayItem(overlayitem);
mapView.getOverlays().add(itemizedoverlay);
}
#Override
public void onProviderDisabled(String provider)
{
}
#Override
public void onProviderEnabled(String provider)
{
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
//Menu with 2 items Refresh and exit
public boolean onCreateOptionsMenu(Menu menu2) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.layout.menumap, menu2);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.refresh:
/*
---------------------------------------------------------------------------------------
code to add in order to refrech the location and position the mobile
on the map using the drawable in the itemizedoverlay. I have tried this :
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
and nothing is changed i still see the old position on the map
and I have tested the app on a sony Ericsson Xperia x10.
I am using google API 10 if this might help.
------------------------------------------------------------------------------------------
*/
return true;
case R.id.exit:
finish();
return true;
}
return false;}
}
Can anyone help me please?
This code should do the trick:
lm.requestSingleUpdate(LocationManager.GPS_PROVIDER, this, null);
Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
lat = loc.getLatitude();
lng = loc.getLongitude();
I am practicing the Android maps now i am getting the maps successfully in my emulator when i search in the Google market i found one Interesting App i am try for to develop the example app is
https://play.google.com/store/apps/details?id=streetdirectory.mobile&feature=search_result#?t=W251bGwsMSwxLDEsInN0cmVldGRpcmVjdG9yeS5tb2JpbGUiXQ..
package com.example.tutorials;
import java.io.IOException;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.location.Geocoder;
import android.location.LocationManager;
import android.os.Bundle;
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.MapView.LayoutParams;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
public class GoogleMap extends MapActivity
{
MapView mapView;
/** Called when the activity is first created. */
#Override
protected boolean isRouteDisplayed()
{
return false;
}
public void changeMap(String area)
{
mapView = (MapView) findViewById(R.id.mapview);
MapController mc=mapView.getController();
GeoPoint myLocation=null;
double lat = 0;
double lng = 0;
try
{
Geocoder g = new Geocoder(this, Locale.getDefault());
java.util.List<android.location.Address> result=g.getFromLocationName(area, 1);
if(result.size()>0){
Toast.makeText(GoogleMap.this, "country: " + String.valueOf(result.get(0).getCountryName()), Toast.LENGTH_SHORT).show();
lat = result.get(0).getLatitude();
lng = result.get(0).getLongitude();
}
else{
Toast.makeText(GoogleMap.this, "record not found", Toast.LENGTH_SHORT).show();
return;
}
}
catch(IOException io)
{
Toast.makeText(GoogleMap.this, "Connection Error", Toast.LENGTH_SHORT).show();
}
myLocation = new GeoPoint(
(int) (lat * 1E6),
(int) (lng * 1E6));
Drawable drawable = this.getResources().getDrawable(R.drawable.icon);
mc.animateTo(myLocation);
mc.setZoom(10);
mapView.invalidate();
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnSearch=(Button) findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText txtSearch=(EditText)findViewById(R.id.txtMapSearch);
String area=txtSearch.getText().toString();
Toast.makeText(GoogleMap.this, "Click-" + String.valueOf(area), Toast.LENGTH_SHORT).show();
GoogleMap.this.changeMap(area);
}
});
mapView = (MapView) findViewById(R.id.mapview);
MapController mapController = mapView.getController();
mapController.setZoom(14);
LinearLayout zoomLayout = (LinearLayout)findViewById(R.id.zoom);
}
}
by this code i am getting search place in Android maps.how can i provide dialog box .when we click on the maps place?
Thanks in Advance......
public class MapViewer extends MapActivity {
MapView mapView;
MapController mapController;
GeoPoint mgeoPoint;
Drawable marker;
MyLocationOverlay mLocationOverlay;
MotionEvent e;
#Override
protected void onCreate(Bundle icicle) {
// TODO Auto-generated method stub
super.onCreate(icicle);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapView);
mapController = mapView.getController();
mapView.setBuiltInZoomControls(true);
mapView.setStreetView(true);
marker = getResources().getDrawable(R.drawable.pushpin);
marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker
.getIntrinsicHeight());
mapView.getOverlays().add(new MapOverlay(marker));
mLocationOverlay = new MyLocationOverlay(this, mapView);
mapView.getOverlays().add(mLocationOverlay);
setViewLocation();
}
#Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
switch (id) {
case 0:
return new AlertDialog.Builder(this).setTitle("Hello").setIcon(
R.drawable.ic_launcher).setPositiveButton("Yes",
new OnClickListener() {
#Override
public void onClick(DialogInterface dialog , int which) {
// TODO Auto-generated method stub
}
}).setCancelable(true).setNegativeButton("Cancel",
new OnClickListener() {
#Override
public void onClick(DialogInterface dialog , int which) {
// TODO Auto-generated method stub
}
})
.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Dismiss",
Toast.LENGTH_SHORT).show();
}
}).create();
default:
break;
}
return null;
}
private void setViewLocation() {
String[] coordinates = { "22.716221", "75.896816" };
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);
mgeoPoint = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
mapController.animateTo(mgeoPoint);
mapController.setZoom(15);
mapView.invalidate();
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
Point scrPoint;
private GeoPoint getPoint(double lat , double lon) {
return (new GeoPoint((int) (lat * 1E6), (int) (lon * 1E6)));
}
class MapOverlay extends
com.google.android.maps.ItemizedOverlay<OverlayItem> {
List<OverlayItem> ListofGeopoints = new ArrayList<OverlayItem>();
public MapOverlay(Drawable defaultMarker ) {
super(defaultMarker);
ListofGeopoints.add(new OverlayItem(getPoint(22.716221, 75.896816),
"IN", "India"));
populate();
}
#Override
protected boolean onTap(int index) {
switch (index) {
case 0:
Toast.makeText(getApplicationContext(), "GeoLocation : 0",
Toast.LENGTH_LONG).show();
showDialog(0);
break;
}
return true;
}
String add = "";
List<Address> add_List = new ArrayList<Address>();
private void getAddress() {
add_List = ReverseGeocode
.getFromLocation(35.594227, -105.223618, 2);
}
#Override
protected OverlayItem createItem(int i) {
return (ListofGeopoints.get(i));
}
#Override
public int size() {
return ListofGeopoints.size();
}
}
}
You can use popup for this .Popup can be displayed any where on screen .just note the c0ordinates of click and display popup on that place.
Below are general example for the same.
Create a layout for your popup
private PopupWindow mPopup;
//Some code here
LayoutInflater inflater = (LayoutInflater)
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//Inflate the view from a predefined XML layout
//This is how your popup will look like
View layout = inflater.inflate(R.layout.popup_layout,
(ViewGroup) findViewById(R.id.popup_element));
mPopup = new PopupWindow(layout, "width", "height", true);
//Use below when you want to display at specific x-y coord on screen
mPopup .showAtLocation(layout, Gravity.CENTER, "x-coord", "y-coord");
//You can use some thing like below to get views from your layout
TextView mText = (TextView) layout.findViewById(R.id."id for textview");
mText.setText("Just an example you can set buttons and listviews in similar fashion");
mPopup.dismiss();//When you want to dismiss Popup
You want to have listView so your layout xml will have a listview. use adapter to fill the listview same way as you do normally.