This is my Map Activity class and i have to extract the current location lat n long points and have to show them on map.And i also have incorporated a search box which will display the location of an address on map. Its showing the location but at difference of 200 meter. And when i reopen it, it always show the previous traced location or searched location. I want to show the extracted lat n long points on map.Please Help me out. Thanks in advance..
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.AlertDialog;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Criteria;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
public class MapViewActivity extends MapActivity implements LocationListener {
private MapView mapView;
Button search;
EditText address;
private LocationManager locationManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
search=(Button)findViewById(R.id.find_loc);
address=(EditText)findViewById(R.id.enter_address);
search.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
address=(EditText)findViewById(R.id.enter_address);
if (address.getText().toString().trim().length() == 0) {
showMessage("Error", "Please enter address!");
return;
}
Geocoder geoCoder = new Geocoder(MapViewActivity.this,
Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocationName(
address.getText().toString(), 1);
// Getting latitude
double latitude = addresses.get(0).getLatitude();
// Getting longitude
double longitude = addresses.get(0).getLongitude();
if (addresses.size() > 0) {
GeoPoint p = new GeoPoint(
(int) ( latitude * 1E6),
(int) (longitude * 1E6));
// Getting MapController
MapController mapController =
mapView.getController();
// Locating the Geographical point in the Map
mapController.animateTo(p);
//Applying a zoom
mapController.setZoom(15);
// Redraw the map
mapView.invalidate();
// Getting list of overlays available in the map
List<Overlay> mapOverlays = mapView.getOverlays();
// Creating a drawable object to represent the
image of mark in the map
Drawable drawable =
MapViewActivity.this.getResources().getDrawable(R.drawable.cur_position);
// Creating an instance of ItemizedOverlay to mark
the current location in the map
CurrentLocationOverlay currentLocationOverlay = new
CurrentLocationOverlay(drawable);
// Creating an item to represent a mark in the
overlay
OverlayItem currentLocation = new OverlayItem(p,
"Current Location", "Latitude : " + latitude + ", Longitude:" + longitude);
// Adding the mark to the overlay
currentLocationOverlay.addOverlay(currentLocation);
// Clear Existing overlays in the map
mapOverlays.clear();
// Adding new overlay to map overlay
mapOverlays.add(currentLocationOverlay);
}
} catch (IOException e) {
e.printStackTrace();
}
catch(Exception e)
{
showMessage("Error", "Address not found!");
e.printStackTrace();
}
}
});
// Getting reference to MapView
mapView = (MapView) findViewById(R.id.map_view);
// Setting Zoom Controls on MapView
mapView.setBuiltInZoomControls(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
//Criteria criteria = new Criteria();
final Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
#Override
public void onBackPressed() {
finish();
}
#Override
public void onDestroy() {
if (locationManager != null) {
locationManager.removeUpdates(this);
}
super.onDestroy();
}
#Override
public void onLocationChanged(Location location) {
// Getting latitude
double latitude = location.getLatitude();
// Getting longitude
double longitude = location.getLongitude();
// Setting latitude and longitude in the TextView tv_location
//tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude
);
// Creating an instance of GeoPoint corresponding to latitude and longitude
GeoPoint point = new GeoPoint((int)(latitude * 1E6), (int)(longitude*1E6));
// Getting MapController
MapController mapController = mapView.getController();
// Locating the Geographical point in the Map
mapController.animateTo(point);
// Applying a zoom
mapController.setZoom(15);
// Redraw the map
mapView.invalidate();
// Getting list of overlays available in the map
List<Overlay> mapOverlays = mapView.getOverlays();
// Creating a drawable object to represent the image of mark in the map
Drawable drawable =
this.getResources().getDrawable(R.drawable.cur_position);
// Creating an instance of ItemizedOverlay to mark the current location in
the map
CurrentLocationOverlay currentLocationOverlay = new
CurrentLocationOverlay(drawable);
// Creating an item to represent a mark in the overlay
OverlayItem currentLocation = new OverlayItem(point, "Current Location",
"Latitude : " + latitude + ", Longitude:" + longitude);
// Adding the mark to the overlay
currentLocationOverlay.addOverlay(currentLocation);
// Clear Existing overlays in the map
mapOverlays.clear();
// Adding new overlay to map overlay
mapOverlays.add(currentLocationOverlay);
}
private void showMessage(final String title, final String message) {
runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder alert = new AlertDialog.Builder(MapViewActivity.this);
alert.setTitle(title);
alert.setPositiveButton("OK", null);
alert.setMessage(message);
alert.show();
}
});
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
and this is my CurrentLocationOverlay class
package com.ceolution.bhinstitute.crm;
import java.util.ArrayList;
import android.graphics.drawable.Drawable;
import android.util.Log;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;
public class CurrentLocationOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
public CurrentLocationOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
// Executed, when populate() method is called
#Override
protected OverlayItem createItem(int arg0) {
return mOverlays.get(arg0);
}
#Override
public int size() {
return mOverlays.size();
}
public void addOverlay(OverlayItem overlay){
mOverlays.add(overlay);
populate(); // Calls the method createItem()
}
#Override
protected boolean onTap(int arg0) {
Log.d("Tapped", mOverlays.get(arg0).getSnippet());
return true;
}
}
// Getting LocationManager object from System Service LOCATION_SERVICE
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
String provider;
if(!isGPSEnabled)
{
provider = LocationManager.NETWORK_PROVIDER;
}
else
provider=LocationManager.GPS_PROVIDER;
locationManager.requestLocationUpdates(provider, 20000, 0, this);
use above code after
// Setting Zoom Controls on MapView
mapView.setBuiltInZoomControls(true);
hope this will help and also you can give alert to user to enable gps.
i'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 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);
}
I have to make a multiple marker google map using JSON parsing. Any one having helping code of it. So that i can gain an idea on it. The activity i have made is not working exactly what i want.
This is my activity
public class MapsActivity extends MapActivity{
private MapController mapControll;
private GeoPoint geoPoint=null;
private MapView mapview;
private MyItemizedOverlay userPicOverlay;
private MyItemizedOverlay nearPicOverlay;
private Drawable userPic,atmPic;
private OverlayItem nearatms[] = new OverlayItem[50];
public static Context context;
public double latitude;
public double longitude;
private List<String> lat = new ArrayList<String>();
private List<String> lon = new ArrayList<String>();
private String[] get_lati;
private String[] get_long;
#Override
protected void onCreate(Bundle icicle) {
// TODO Auto-generated method stub
super.onCreate(icicle);
context = getApplicationContext();
setContentView(R.layout.map);
lat.clear();
lon.clear();
Intent in = getIntent();
if(in!=null){
get_lati = in.getStringArrayExtra("LAT_KEY");
get_long = in.getStringArrayExtra("LONG_KEY");
System.out.println("lat===="+get_lati.length+" lon==="+get_long.length);
}
for(int i = 0;i<get_lati.length;i++){
String lt = null;
String ln = null;
lt =get_lati[i];
ln =get_long[i];
System.out.println("lt=="+lt+"==ln=="+ln);
}
showMap();
}
public void showMap() {
// TODO Auto-generated method stub
try {
double lat_dbl = Double.parseDouble(get_lati[0]);
double lon_dbl = Double.parseDouble(get_long[0]);
geoPoint = new GeoPoint((int)(lat_dbl * 1E6),(int)(lon_dbl * 1E6));
mapview = (MapView)findViewById(R.id.mapView);
mapControll= mapview.getController();
mapview.setBuiltInZoomControls(true);
mapview.setStreetView(true);
mapControll.setZoom(16);
mapControll.animateTo(geoPoint);
userPic = this.getResources().getDrawable(R.drawable.pin);
userPicOverlay = new MyItemizedOverlay(userPic);
OverlayItem overlayItem = new OverlayItem(geoPoint, "I'm Here!!!", null);
userPicOverlay.addOverlay(overlayItem);
mapview.getOverlays().add(userPicOverlay);
atmPic = this.getResources().getDrawable(R.drawable.pin);
nearPicOverlay = new MyItemizedOverlay(atmPic);
for (int i = 0; i < 5; i++) {
nearatms[i] = new OverlayItem(new GeoPoint((int)((latitude) * 1E6), i),"Name", null);//just check the brackets i just made change here so....
nearPicOverlay.addOverlay(nearatms[i]);
}
mapview.getOverlays().add(nearPicOverlay);
//Added symbols will be displayed when map is redrawn so force redraw now
mapview.postInvalidate();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
public class MyItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> myOverlays ;
public MyItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
myOverlays = new ArrayList<OverlayItem>();
populate();
}
public void addOverlay(OverlayItem overlay){
myOverlays.add(overlay);
populate();
}
#Override
protected OverlayItem createItem(int i) {
return myOverlays.get(i);
}
// Removes overlay item i
public void removeItem(int i){
myOverlays.remove(i);
populate();
}
// Returns present number of items in list
#Override
public int size() {
return myOverlays.size();
}
public void addOverlayItem(OverlayItem overlayItem) {
myOverlays.add(overlayItem);
populate();
}
public void addOverlayItem(int lat, int lon, String title) {
try {
GeoPoint point = new GeoPoint(lat, lon);
OverlayItem overlayItem = new OverlayItem(point, title, null);
addOverlayItem(overlayItem);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
#Override
protected boolean onTap(int index) {
// TODO Auto-generated method stub
String title = myOverlays.get(index).getTitle();
//Toast.makeText(MapActivity.this, title, Toast.LENGTH_LONG).show();
return super.onTap(index);
}
}
}
You are creating a geopoint with latitude but 'i' instead of longitude.
new GeoPoint((int)((latitude) * 1E6), i)
instead of:
new GeoPoint((int)((latitude) * 1E6), (int)((longitude) * 1E6)) // + some variation based on i
Thus all the points fall very near to each other.
I assume that you're using 'i' in order to create separate point near your location, and that in the final product you would use an ATM point DB. I suggest that you create a function that is supposed to retrieve ATM locations, and for testing purposes either return fixed (but real) locations, or randomize around your lat/lng. (This is also a better coding practice.)
For debug purposes, log the actual points you are creating, after you created them. if all lat/lng numbers look the same, you have a clue at what's going on. if only two points are logged... that's a different problem. :-)