i'm trying to make the google maps display a route from user current location to the overlay that user tap.
this's my overlay code
public class AddItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> mapOverlays = new ArrayList<OverlayItem>();
private Context context;
public AddItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
public AddItemizedOverlay(Drawable defaultMarker, Context context) {
this(defaultMarker);
this.context = context;
}
#Override
public boolean onTouchEvent(MotionEvent event, MapView mapView)
{
if (event.getAction() == 1) {
GeoPoint geopoint = mapView.getProjection().fromPixels(
(int) event.getX(),
(int) event.getY());
// latitude
double lat = geopoint.getLatitudeE6() / 1E6;
// longitude
double lon = geopoint.getLongitudeE6() / 1E6;
// Toast.makeText(context, "Lat: " + lat + ", Lon: "+lon, Toast.LENGTH_SHORT).show();
}
return false;
}
#Override
protected OverlayItem createItem(int i) {
return mapOverlays.get(i);
}
#Override
public int size() {
return mapOverlays.size();
}
#Override
protected boolean onTap(int index) {
final OverlayItem item = mapOverlays.get(0);
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.setPositiveButton("Arahkan", new OnClickListener() {
//arahkan atau direction
public void onClick(DialogInterface arg0, int arg1) {
// Getting intent data
Intent i = getIntent();
// Users current geo location
String user_latitude = i.getStringExtra("user_latitude");
String user_longitude = i.getStringExtra("user_longitude");
// Geopoint to place on map
//geoPoint = new GeoPoint((int) (Double.parseDouble(user_latitude) * 1E6),
// (int) (Double.parseDouble(user_longitude) * 1E6));
StringBuilder urlString = new StringBuilder();
String saddr = newLocation.getLatitude(user_latitude)+","+newLocation.getLongitude(user_longitude);
String daddr = (item.getPoint().getLatitudeE6()/1E6)+","+(item.getPoint().getLongitudeE6()/1E6);
urlString.append("http://maps.google.com/maps?f=d&hl=en");
urlString.append("&saddr="+saddr);
urlString.append("&daddr="+daddr);
Intent ii = new Intent(Intent.ACTION_VIEW, Uri.parse(urlString.toString()));
context.startActivity(i);
}
private Intent getIntent() {
// TODO Auto-generated method stub
return null;
}
});
dialog.show();
return true;
}
private MapView findViewById(int mapview2) {
// TODO Auto-generated method stub
return null;
}
public void addOverlay(OverlayItem overlay) {
mapOverlays.add(overlay);
}
public void populateNow(){
this.populate();
}
}
please give me your opinion, i'd appreciate it if there's some1 wanna fix my code problem.
thanks. :)
I want show own loaction from a address was input by user use LocationOverlay and show position by a small dot or anything by icon....(ex: can show this position by a flag.png )But now i don't know how show it on map.Can you help me!
source code:
public class Main extends MapActivity implements LocationListener {
private static double lat;
private static double lon;
private MapController mapControl;
private MapView mapView;
LocationManager locman;
Location loc;
String provider = LocationManager.GPS_PROVIDER;
String TAG = "GPStest";
Bundle locBundle;
private int numberSats = -1;
private float satAccuracy = 2000;
private float bearing;
private double altitude;
private float speed;
private String currentProvider;
private TextView txt;
private double lat1;
private double lon1;
private Drawable marker;
private Geocoder gcoder;
private MyLocationOverlay me = null;
long GPSupdateInterval; // In milliseconds
float GPSmoveInterval; // In meters
private MyMyLocationOverlay myLocationOverlay;
private List<Overlay> mapOverlays;
public DisplayOverlay displayOverlay;
private EditText address;
Button test;
private Button btnMylocation;
private Button btnAddrress;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_long_van_map);
gps();
btnMylocation = (Button) findViewById(R.id.button1);
// get my location
btnMylocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
gps();
}
});
gcoder = new Geocoder(this);
me = new MyLocationOverlay(this, mapView);
address = (EditText) findViewById(R.id.editText1);
btnAddrress = (Button) findViewById(R.id.button2);
//Get postion from address
btnAddrress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String add = address.getText().toString();
try {
List<Address> addresses = gcoder
.getFromLocationName(add, 1);
if (addresses == null) {
// return point;
}
// just get first item of list address
Address add2 = addresses.get(0);
lat1 = add2.getLatitude();
lon1 = add2.getLongitude();
} catch (IOException e) {
}
GeoPoint newPoint = new GeoPoint((int) (lat1 * 1e6),
(int) (lon1 * 1e6));
mapControl.animateTo(newPoint);
marker = getResources().getDrawable(R.drawable.startpoint);
marker.setBounds(0, 0, marker.getIntrinsicWidth(),
marker.getIntrinsicHeight());
//mapView.getOverlays().add(new SitesOverlay(marker));
mapView.getOverlays().add(me);
}
});
}
//Info gps of me
public void gps() {
updateGPSprefs();
locman = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Listener for GPS Status...
final GpsStatus.Listener onGpsStatusChange = new GpsStatus.Listener() {
public void onGpsStatusChanged(int event) {
switch (event) {
case GpsStatus.GPS_EVENT_STARTED:
// Started...
break;
case GpsStatus.GPS_EVENT_FIRST_FIX:
// First Fix...
Toast.makeText(Main.this, "GPS has First fix",
Toast.LENGTH_LONG).show();
break;
case GpsStatus.GPS_EVENT_STOPPED:
// Stopped...
break;
case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
// Satellite update
break;
}
//GpsStatus status = locman.getGpsStatus(null);
// Not presently doing anything with following status list for
// individual satellites
// Iterable<GpsSatellite> satlist = status.getSatellites();
}
};
locman.addGpsStatusListener(onGpsStatusChange);
locman.requestLocationUpdates(provider, GPSupdateInterval,
GPSmoveInterval, this);
Log.i(TAG, locman.toString());
// Add map controller with zoom controls
mapView = (MapView) findViewById(R.id.Mapview);
mapView.setSatellite(false);
mapView.setTraffic(false);
mapView.setBuiltInZoomControls(true); // Set android:clickable=true in
// main.xml
int maxZoom = mapView.getMaxZoomLevel();
int initZoom = (int) (0.95 * (double) maxZoom);
mapControl = mapView.getController();
mapControl.setZoom(initZoom);
// Set up compass and dot for present location map overlay
List<Overlay> overlays = mapView.getOverlays();
myLocationOverlay = new MyMyLocationOverlay(this, mapView);
overlays.add(myLocationOverlay);
// Set up overlay for data display
displayOverlay = new DisplayOverlay();
mapOverlays = mapView.getOverlays();
mapOverlays.add(displayOverlay);
txt = (TextView) findViewById(R.id.textView1);
txt.setText(LongVanMap.gettext());
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
// Called when location has changed
centerOnLocation();
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
locman.removeUpdates(this);
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
locman.requestLocationUpdates(provider, GPSupdateInterval,
GPSmoveInterval, this);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
centerOnLocation();
}
// Method to assign GPS prefs
public void updateGPSprefs() {
int gpsPref = Integer.parseInt(Prefs
.getGPSPref(getApplicationContext()));
switch (gpsPref) {
case 1:
GPSupdateInterval = 5000; // milliseconds
GPSmoveInterval = 1; // meters
break;
case 2:
GPSupdateInterval = 10000;
GPSmoveInterval = 100;
break;
case 3:
GPSupdateInterval = 125000;
GPSmoveInterval = 1000;
break;
}
}
}
#Override
protected void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.maps_screen);
initActionBar();
String address = getIntent().getExtras().getString("address");
String title = getIntent().getExtras().getString("title");
MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
Geocoder geoCoder = new Geocoder(this);
List<Address> addresses;
try {
Log.i("maps", "getting geopoint for address: " + address);
addresses = geoCoder.getFromLocationName(address, 1);
if (addresses == null || addresses.isEmpty()) {
Log.i("maps", "couldn't get any matches for the following address: " + address);
isInvalidLocation = true;
showInvalidAddressDialog();
return;
}
Address location = addresses.get(0);
GeoPoint point = coordinatesToGeoPoint(location.getLatitude(), location.getLongitude());
Drawable marker = getResources().getDrawable(R.drawable.da_marker_red);
MapOverlay adPos = new MapOverlay(marker,mapView);
List<Overlay> overlays = mapView.getOverlays();
OverlayItem overlayItem = new OverlayItem(point, title, address);
adPos.addOverlay(overlayItem);
overlays.add(adPos);
MapController mapcontroller = mapView.getController();
mapcontroller.animateTo(point);
mapcontroller.setCenter(point);
mapcontroller.setZoom(12);
} catch (Exception ex) {
Log.e("geocoder", "error using geocoder", ex);
}
}
I've created my own custom map to show my current location and multiple points on map. it works fine,but now i would like to show a route from my current location to every point on the map.Can you give me some suggestions how i can do that? thx.
this is my customMap activity:
public class CustomMapActivity extends MapActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
String provider = "";
Criteria crit = new Criteria();
Location loc = new Location("");
LocationManager mlocManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.marker);
ItemizedOverlayedClass itemizedoverlay = new ItemizedOverlayedClass(drawable, this);
try
{
MyLocationOverlay mylocationOverlay = new MyLocationOverlay(this, mapView);
mylocationOverlay.enableMyLocation();
mapView.getOverlays().add(mylocationOverlay);
provider = mlocManager.getBestProvider(crit, false);
loc = mlocManager.getLastKnownLocation(provider);
}
catch(Exception ex)
{
//Toast.makeText(this, "Unable to retrive provider", Toast.LENGTH_LONG).show();
}
for (ServiceActivity activity : DataSources.ActivitiesList)
{
try
{
Location siteLocation = new Location("");
siteLocation.setLatitude(activity.SiteLatitude);
siteLocation.setLongitude(activity.SiteLongitude);
GeoPoint point = new GeoPoint((int)(activity.SiteLatitude * 1e6),(int)(activity.SiteLongitude * 1e6));
OverlayItem overlayitem = new OverlayItem(point, activity.SiteName+ " " + activity.SiteAddress, "Distance to this location: " + String.valueOf(loc.distanceTo(siteLocation)/1000) + " km");
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
}
catch(Exception ex)
{
#SuppressWarnings("unused")
AlertDialogClass alert = new AlertDialogClass(this,ex.getMessage());
}
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
//mylocationOverlay.enableMyLocation();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_map, menu);
return true;
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
and this is the overlay class:
package com.example.srwebservice;
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 ItemizedOverlayedClass extends ItemizedOverlay {
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
Context mContext;
public ItemizedOverlayedClass(Drawable defaultMarker)
{
super(boundCenterBottom(defaultMarker));
// TODO Auto-generated constructor stub
}
public ItemizedOverlayedClass(Drawable defaultMarker, Context context)
{
super(boundCenterBottom(defaultMarker));
mContext = context;
}
#Override
protected OverlayItem createItem(int i)
{
// TODO Auto-generated method stub
return mOverlays.get(i);
}
#Override
public int size()
{
return mOverlays.size();
}
public void addOverlay(OverlayItem overlay)
{
mOverlays.add(overlay);
populate();
}
#Override
protected boolean onTap(int index) {
OverlayItem item = mOverlays.get(index);
AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.show();
return true;
}
}
This link have tutorial to draw route path on map in our app. this may help you and
use below to link with map app... this will take to you in google map application
String uri = "http://maps.google.com/maps?f=d&hl=en&saddr="+source_latitude+","+source_longitude+"&daddr="+destination_latitude+","+destination_longitude;
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(uri));
intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
startActivity(intent);
OR
refter this link how to display the driving routes
i found a simpler solution.I can use google maps intent directly, and i don't need to create a custom map activity anymore:
if(DataSources.ActivitiesList.length >0)
{
String address = "http://maps.google.com/maps?daddr=" + DataSources.ActivitiesList[0].SiteLatitude.toString() + "," + DataSources.ActivitiesList[0].SiteLongitude.toString();
for (int i= 1 ;i < DataSources.ActivitiesList.length ; i++)
{
if(DataSources.ActivitiesList[i].SiteLatitude != null)
address += "+to:" + DataSources.ActivitiesList[i].SiteLatitude + "," + DataSources.ActivitiesList[i].SiteLongitude;
}
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(address));
startActivity(intent);
break;
}
I need some way to move bus icon on a roads in mapview.
I have GeoPoint Array with all the Coordinates Longtitude and Latitude points where a bus needed to pass, Also i need to create some "Displacement Animation" along the route
I use Overlay class to setting a bus icon every 1 second
class BusOverlay extends ItemizedOverlay<OverlayItem> {
private Context context = null;
private List<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
private MediaPlayer mediaPop;
public BusOverlay(Drawable defaultMarker, Context context) {
super(boundCenterBottom(defaultMarker));
this.context = context;
}
#Override
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
#Override
public int size() {
return mOverlays.size();
}
public void addOverlayItem(OverlayItem overlayItem) {
mOverlays.add(overlayItem);
populate();
}
public void addOverlayItem(int lat, int lon, String title) {
GeoPoint point = new GeoPoint(lat, lon);
OverlayItem overlayItem = new OverlayItem(point, title, title);
addOverlayItem(overlayItem);
}
public void removeOverlay(OverlayItem overlay) {
mOverlays.remove(overlay);
populate();
}
public void removeOverlayItem(int lat, int lon, String title) {
GeoPoint point = new GeoPoint(lat, lon);
OverlayItem overlayItem = new OverlayItem(point, title, title);
removeOverlay(overlayItem);
}
protected boolean onTap(int index) {
super.onTap(index);
return true;
}
}
In My Activity class i used with Runable methode
Drawable busLocationIcon = this.getResources().getDrawable(
R.drawable.bus_location);
final BusOverlay itemizedBusLocartionOverlay = new BusOverlay(
busLocationIcon, this);
int countBus = 0;
myRunnable = new Runnable() {
public void run() {
try {
itemizedBusLocartionOverlay.addOverlayItem((int) (Double
.parseDouble(Main.jsonArrayBus.getJSONObject(
countBus).getString("StopLat")) * 1000000),
(int) (Double.parseDouble(Main.jsonArrayBus
.getJSONObject(countBus).getString(
"StopLon")) * 1000000), "The Bus");
countBus++;
mapView.getOverlays().add(itemizedBusLocartionOverlay);
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Hendler
h.postDelayed(myRunnable, 1000);
}
};
h.postDelayed(myRunnable, 1000);
But it is not working good..
please help me.
I am making an app in which i have a navigation screen where the user can give in multiple locations.
Those locations are stored in a array string.
I am using that string in my map class and i want to show al the locations on the map with a marker.
Only the last location stored in the array shows up.
Can anybody help me please.
My Navigation class
public class Navigatie extends Activity{
public static String plaats1;
public static String plaats2;
public GeoPoint p;
public static String[] plaats;
public int i = 0;
static final String[] COUNTRIES = new String[]
{
"Antwerpen", "Aalst", "Aartselaar", "Brussel", "Charleroi","duinkerke", "Gent", "Hasselt", "Ieper", ""
};
// Here we create the layout, everything that's needed on the form is loaded in here.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigatie);
// Create an instance of the AutoCompleteTextView which is created in the layout file
AutoCompleteTextView textView=(AutoCompleteTextView)findViewById(R.id.autocomplete);
// Create an ArrayAdapter which we are using to autocomplete the textview
ArrayAdapter<String>adapter=new ArrayAdapter<String>(this,R.layout.item_list,COUNTRIES);
// put the adapter created above in the AutoCompleteTextView
textView.setAdapter(adapter);
// We create a new ImageButton which links to the map.java class
ImageButton imageButton = (ImageButton) findViewById(R.id.imageButton1);
// We give a onclicklistener method to the button imageButton
imageButton.setOnClickListener(new OnClickListener() {
// if the imageButton is clicked we start a new activity called "Map"
public void onClick(View v) {
/*
for (int j = 0; j<plaats.length; j++)
{
Map.plaats[j] = plaats[j];
}
*/
startActivity(new Intent(Navigatie.this, Map.class));
}
});
Button add = (Button)findViewById(R.id.toevoegen);
add.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
EditText text1 = (EditText)findViewById(R.id.autocomplete);
plaats1 = text1.getText().toString();
if (plaats1 != "")
{
EditText text2 = (EditText)findViewById(R.id.editText1);
text2.append(plaats1 + "\n");
plaats = new String[20];
plaats[i] = plaats1;
Toast.makeText(Navigatie.this, plaats[i], Toast.LENGTH_SHORT).show();
i++;
text1.setText("");
}
}
});
Button clear = (Button)findViewById(R.id.verwijderen);
clear.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
EditText text2 = (EditText)findViewById(R.id.editText1);
text2.setText("");
Arrays.fill(plaats, null);
}
});
}
}
My Map class:
public class Map extends MapActivity {
private MapView mapView;
private MapController mc;
LocationManager locMgr;
MyLocationListener locLstnr;
private TextView tvlat;
private TextView tvlong;
public Navigatie nav;
public String locatie;
public int coordinates[] = new int[100];
public int counter = 0;
int gplat;
int gplon;
static final String[] COUNTRIES = new String[]
{
"Antwerpen", "Aalst", "Aartselaar", "Brussel", "Charleroi","duinkerke", "Gent", "Hasselt", "Ieper", ""
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// set the layout screen to map
setContentView(R.layout.map);
// Create an instance of the AutoCompleteTextView which is created in the layout file
AutoCompleteTextView textView=(AutoCompleteTextView)findViewById(R.id.autocomplete_country);
// Create an ArrayAdapter which we are using to autocomplete the textview
ArrayAdapter<String>adapter=new ArrayAdapter<String>(this,R.layout.item_list,COUNTRIES);
// put the adapter created above in the AutoCompleteTextView
textView.setAdapter(adapter);
// Setting the mapview1 to the instance of MapView
mapView = (MapView) findViewById(R.id.mapview1);
// giving a controller to mc
mc = mapView.getController();
// String location2 = Navigatie.getVariable();
for (int i = 0; i<Navigatie.plaats.length; i++)
{
if(Navigatie.plaats[i]!=null && !Navigatie.plaats[i].equals(""))
{
FindLocation(Navigatie.plaats[i]);
}
else
{
System.out.println("Locatie niet gevonden");
}
}
// create an instance of the find button created in the layout file
Button btn_find = (Button) findViewById(R.id.btn_find);
// Defining button click event listener for the find button
OnClickListener findClickListener = new OnClickListener()
{
public void onClick(View v)
{
// Getting reference to EditText to get the user input location
EditText etLocation = (EditText) findViewById(R.id.autocomplete_country);
// Getting user input location
String location = etLocation.getText().toString();
if(location!=null && !location.equals(""))
{
Toast.makeText(Map.this, "Inzoomend op " + location, Toast.LENGTH_SHORT).show();
new GeocoderTask().execute(location);
}
else
{
Toast.makeText(Map.this, "Locatie niet gevonden", Toast.LENGTH_SHORT).show();
}
}
};
// Setting button click event listener for the find button
btn_find.setOnClickListener(findClickListener);
// redraws the map
mapView.invalidate();
// sets the built in zoomcontrols on the screen
mapView.setBuiltInZoomControls(true);
Drawable makerDefault = this.getResources().getDrawable(R.drawable.pushpin);
MirItemizedOverlay itemizedOverlay = new MirItemizedOverlay(makerDefault);
GeoPoint point = null;
for (int i = 0; i<100; i++)
{
point = new GeoPoint(coordinates[i], coordinates[i+1]);
OverlayItem overlayItem = new OverlayItem(point, "new place added", null);
itemizedOverlay.addOverlayItem(overlayItem);
i++;
}
mapView.getOverlays().add(itemizedOverlay);
MapController mc = mapView.getController();
mc.setCenter(point);
/*
String provider = LocationManager.GPS_PROVIDER;
locMgr = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locLstnr = new MyLocationListener();
locMgr.requestSingleUpdate(provider, null);
*/
List<Overlay> mapOverlays = mapView.getOverlays();
Projection projection = mapView.getProjection();
}
// when the form is created we put in the menu from the resources menu.
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// we get the menu called main from the resources menu
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
// we set the options for the menu parts
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
// if my location is touched, this code is executed
case R.id.my_location:
// creates a toast that displays "moving to current location"
Toast.makeText(Map.this, "Moving To Current location", Toast.LENGTH_SHORT).show();
String provider = LocationManager.GPS_PROVIDER;
locMgr = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locLstnr = new MyLocationListener();
locMgr.requestSingleUpdate(provider, null);
// locLstnr.gpsCurrentLocation();
return true;
// if normal view is touched, this code is executed
case R.id.normalview:
// creates a toast that displays "Map Normal Street View"
Toast.makeText(Map.this, "Map Normal Street View", Toast.LENGTH_SHORT).show();
// if the satellite view is enabled, we disable the satellite view so the normal view popups again
if(mapView.isSatellite()==true){
mapView.setSatellite(false);
}
return true;
case R.id.satellite:
// creates a toast that displays "Map Satellite view"
Toast.makeText(Map.this, "Map Satellite View", Toast.LENGTH_SHORT).show();
// if the satellite view is disabled we enable the satellite view
if(mapView.isSatellite()==false){
mapView.setSatellite(true);
}
}
return true;
}
#Override
protected boolean isRouteDisplayed()
{
// TODO Auto-generated method stub
return true;
}
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();
Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_SHORT).show();
String coordinates[] = {""+loc.getLatitude(), ""+loc.getLongitude()};
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);
GeoPoint p = new GeoPoint(
(int) (lat * 1E6),
(int) (lng * 1E6));
mc.animateTo(p);
mc.setZoom(7);
mapView.invalidate();
}
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)
{
}
}
// My overlay Class starts
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.pushpin),
screenPoint.x, screenPoint.y , null); //Setting the image location on the screen (x,y).
}
}
// My overlay Class ends
private class MirItemizedOverlay extends ItemizedOverlay
{
private List<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
public MirItemizedOverlay(Drawable defaultMarker)
{
super(boundCenterBottom(defaultMarker));
}
#Override
protected OverlayItem createItem(int i)
{
return mOverlays.get(i);
}
#Override
public int size()
{
return mOverlays.size();
}
public void addOverlayItem(OverlayItem overlayItem)
{
mOverlays.add(overlayItem);
populate();
}
public void addOverlayItem(int lat, int lon, String title)
{
GeoPoint point = new GeoPoint(lat, lon);
OverlayItem overlayItem = new OverlayItem(point, title, null);
addOverlayItem(overlayItem);
}
/*
#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());
Toast.makeText(getBaseContext(),
p.getLatitudeE6() / 1E6 + "," +
p.getLongitudeE6() /1E6 ,
Toast.LENGTH_SHORT).show();
Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
try
{
List<Address> addresses = geoCoder.getFromLocation(p.getLatitudeE6() / 1E6, p.getLongitudeE6() / 1E6, 1);
String strCompleteAddress= "";
if (addresses.size() > 0)
{
for (int i=0; i<addresses.get(0).getMaxAddressLineIndex();i++)
strCompleteAddress+= addresses.get(0).getAddressLine(i) + "\n";
}
Log.i("MyLocTAG => ", strCompleteAddress);
Toast.makeText(getBaseContext(), strCompleteAddress, Toast.LENGTH_LONG).show();
}
catch (IOException e)
{
Log.i("MyLocTAG => ", "this is the exception part");
e.printStackTrace();
}
return true;
}
else
return false;
}*/
}
//An AsyncTask class for accessing the GeoCoding Web Service
private class GeocoderTask extends AsyncTask<String, Void, List<Address>>
{
protected List<Address> doInBackground(String... locationName)
{
// Creating an instance of Geocoder class
Geocoder geocoder = new Geocoder(getBaseContext());
List<Address> addresses = null;
try {
//Getting a maximum of 3 Address that matches the input text
addresses = geocoder.getFromLocationName(locationName[0], 3);
}
catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
protected void onPostExecute(List<Address> addresses)
{
//Getting Reference to MapView of the layout activity_main
MapView mapView = (MapView) findViewById(R.id.mapview1);
// Setting ZoomControls
mapView.setBuiltInZoomControls(true);
// Getting MapController for the MapView
MapController mc = mapView.getController();
// Getting Drawable object corresponding to a resource image
Drawable drawable = getResources().getDrawable(R.drawable.pushpin);
// Getting Overlays of the map
List<Overlay> overlays = mapView.getOverlays();
// Creating an ItemizedOverlay
LocationOverlay locationOverlay = new LocationOverlay(drawable,getBaseContext());
// Clearing the overlays
overlays.clear();
if(addresses==null || addresses.size()==0)
{
Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
// Redraws the map to clear the overlays
mapView.invalidate();
}
// Adding Markers on Google Map for each matching address
for(int i=0;i<addresses.size();i++)
{
Address address = (Address) addresses.get(i);
// Creating an instance of GeoPoint, to display in Google Map
GeoPoint p = new GeoPoint((int)(address.getLatitude()*1E6), (int)(address.getLongitude()*1E6));
String addressText = String.format("%s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getCountryName());
// Creating an OverlayItem to mark the point
OverlayItem overlayItem = new OverlayItem(p, "Location",addressText);
// Adding the OverlayItem in the LocationOverlay
locationOverlay.addOverlay(overlayItem);
// Adding locationOverlay to the overlay
overlays.add(locationOverlay);
// Locate the first location
if(i==0)
mc.animateTo(p);
mc.setZoom(15);
}
// Redraws the map
mapView.invalidate();
}
}
public void FindLocation(String plaats)
{
Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocationName(
plaats, 5);
//String add = "";
if (addresses.size() > 0) {
coordinates[counter] = (int) (addresses.get(0).getLatitude() * 1E6);
counter++;
coordinates[counter] = (int) (addresses.get(0).getLongitude() * 1E6);
counter++;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
a few hints:
On FindLocation add an else to catch not found locations:
public void FindLocation(String plaats) {
Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocationName(
plaats, 5);
//String add = "";
if (addresses.size() > 0) {
coordinates[counter] = (int) (addresses.get(0).getLatitude() * 1E6);
counter++;
coordinates[counter] = (int) (addresses.get(0).getLongitude() * 1E6);
counter++;
} else {
Log.v(TAG, "Site " + plaats + " not found!");
}
} catch (IOException e) {
e.printStackTrace();
}
}
Also in onCreate() loop over already defined locations, not the whole array:
for (int i = 0; i<count; i+=2)
{
point = new GeoPoint(coordinates[i], coordinates[i+1]);
OverlayItem overlayItem = new OverlayItem(point, "new place added", null);
itemizedOverlay.addOverlayItem(overlayItem);
}