Using array to show different points on map - android

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);
}

Related

Android:Google map current location and other marker points

I'm developing an android Google map app. How to create a current location ,balloon overlay and other marker location points.
I am creating Other marker location points in (CustomMap.java)
Here I want to current location also.Please help me
CustomMap.java
public class CustomMap extends MapActivity implements LocationListener {
MapView mapView;
List<Overlay> mapOverlays;
Drawable drawable;
Drawable drawable2;
CustomItemizedOverlay<CustomOverlayItem> itemizedOverlay;
CustomItemizedOverlay<CustomOverlayItem> itemizedOverlay2;
double longitude;
double latitude;
long start;
long stop;
int x, y;
int lati = 0;
int longit = 0;
GeoPoint touchedPoint;
public boolean overlay_status=false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// making it full screen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_custom_map);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapOverlays = mapView.getOverlays();
// first overlay
drawable = getResources().getDrawable(R.drawable.marker);
itemizedOverlay = new CustomItemizedOverlay<CustomOverlayItem>(drawable, mapView);
//first overlay in first pinpoint
GeoPoint point = new GeoPoint((int)(13.0094444*1E6),(int)(77.5508333*1E6));
CustomOverlayItem overlayItem = new CustomOverlayItem(point, "ISKCON Temple Bangalore(1997)",
"(ISKCON Temple, Chord Rd, Mahalakshmipuram Layout, Nagapura, Bangalore, Karnataka, India)",
"http://www.iskcon-bda.org/data/HKH.jpg");
itemizedOverlay.addOverlay(overlayItem);
//first overlay in second pinpoint
GeoPoint point2 = new GeoPoint((int)(12.8008*1E6),(int)(77.5756*1E6));
CustomOverlayItem overlayItem2 = new CustomOverlayItem(point2, "Bannerghatta National Park",
"(Bannerghatta Biological Park is carved out of the Bannerghatta National Park in the year 2002)",
"http://www.google.co.in/imgres?imgurl=http://travel.sulekha.com/" +
"india/karnataka/bangalore/photos/bannerghatta-national-park-25.jpg&imgrefurl=http://travel.sulekha.com/" +
"a-visit-to-bannerghatta-national-park_bangalore-travelogue-3541.htm&h=194&w=259&sz=1&tbnid=K5TNPwXHgihgRM:&tbnh=" +
"119&tbnw=160&zoom=1&usg=__MFNGL1C2InXP7jw7XmEi4ym45NY=&docid=d78iF3T5ditWeM&itg=1&hl=en&sa=X&ei=" +
"CpwQUdOmHIPUrQe0m4H4Bg&sqi=2&ved=0CHwQ_B0wCw");
itemizedOverlay.addOverlay(overlayItem2);
mapOverlays.add(itemizedOverlay);
// second overlay
drawable2 = getResources().getDrawable(R.drawable.marker2);
itemizedOverlay2 = new CustomItemizedOverlay<CustomOverlayItem>(drawable2, mapView);
//second overlay in third pinpoint
GeoPoint point3 = new GeoPoint((int)(12.8339956*1E6),(int)(77.4009816*1E6));
CustomOverlayItem overlayItem3 = new CustomOverlayItem(point3, "Wonderla Bangalore(2005)",
"(Wonderla is an amusement park located near Bidadi, 28 kilometres Bangalore, spanning 82 acres of land)",
"http://www.google.co.in/imgres?imgurl=http://www.yohyoh.com/places-tourism/pictures/wb3.jpg&imgrefurl=http://" +
"www.yohyoh.com/places-tourism/view.php/popular-tours/Karnataka/Bangalore/wonderla-bangalore/561/8192987807&h=" +
"194&w=259&sz=1&tbnid=RoLC5gzRHP6VSM:&tbnh=160&tbnw=213&zoom=1&usg=__ShDQAmQ0zjQaKbsy0A63BokHAmk=" +
"&docid=J1aN09WXjvHw4M&itg=1&hl=en&sa=X&ei=Sp0QUbvIEMHjrAfTy4GgBA&ved=0CNMBEPwdMAo");
itemizedOverlay2.addOverlay(overlayItem3);
//second overlay in third pinpoint
GeoPoint point4 = new GeoPoint((int)(12.8385923*1E6),(int)(77.661710599*1E6));
CustomOverlayItem overlayItem4 = new CustomOverlayItem(point4, "Wipro Technologies,Bangalore",
"(Wipro Technologies, Electronics City Phase 1, Electronics City, Bangalore, Karnataka 560100, India)",
"http://www.electronic-city.in/companies/profile/wipro/wipro-electronic-city.jpg");
itemizedOverlay2.addOverlay(overlayItem4);
mapOverlays.add(itemizedOverlay2);
// 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();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
// 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);
String address = "";
Geocoder geoCoder = new Geocoder(
getBaseContext(), Locale.getDefault());
latitude = location.getLatitude();
// Getting longitude
longitude = location.getLongitude();
// Creating an instance of GeoPoint corresponding to latitude and longitude
GeoPoint point5 = new GeoPoint((int)(latitude * 1E6), (int)(longitude*1E6));
try {
List<Address> addresses = geoCoder.getFromLocation(
point.getLatitudeE6() / 1E6,
point.getLongitudeE6() / 1E6, 1);
if (addresses.size() > 0) {
for (int index = 0; index < addresses.get(0).getMaxAddressLineIndex(); index++)
address += addresses.get(0).getAddressLine(index) + " ";
}
tvLocation.setText("Address :" + address );
}
catch (IOException e) {
e.printStackTrace();
}
drawable = getResources().getDrawable(R.drawable.url);
itemizedOverlay = new CustomItemizedOverlay<CustomOverlayItem>(drawable, mapView);
mapView.getOverlays().add(itemizedOverlay);
itemizedOverlay.runOnFirstFix(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
mapView.getOverlays().add(itemizedOverlay);
}
});
MapController mapController = mapView.getController();
// Locating the Geographical point in the Map
mapController.animateTo(point5);
itemizedOverlay.enableMyLocation();
mapView.postInvalidate();
// Getting list of overlays available in the map
List<Overlay> mapOverlays = mapView.getOverlays();
CustomOverlayItem currentLocation = new CustomOverlayItem(point, "Current Location", "Latitude : " + latitude + ", Longitude:" + longitude, null);
// Adding the mark to the overlay
itemizedOverlay.addOverlay(currentLocation);
// Clear Existing overlays in the map
mapOverlays.clear();
mapOverlays.add(itemizedOverlay);
if (savedInstanceState == null) {
//Contains Displaying the pinpoint
final MapController mc = mapView.getController();
mc.animateTo(point);
mc.setZoom(16);
}else {
// example restoring focused state of overlays
int focused;
focused = savedInstanceState.getInt("focused_1", -1);
if (focused >= 0) {
itemizedOverlay.setFocus(itemizedOverlay.getItem(focused));
}
focused = savedInstanceState.getInt("focused_2", -1);
if (focused >= 0) {
itemizedOverlay2.setFocus(itemizedOverlay2.getItem(focused));
}
}
Touchy t = new Touchy();
mapOverlays = mapView.getOverlays();
mapOverlays.add(t);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// example saving focused state of overlays
if (itemizedOverlay.getFocus() != null) outState.putInt("focused_1", itemizedOverlay.getLastFocusedIndex());
if (itemizedOverlay2.getFocus() != null) outState.putInt("focused_2", itemizedOverlay2.getLastFocusedIndex());
super.onSaveInstanceState(outState);
}
//Contains creating the option menu items
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 0, 1, "Remove Overlay");
menu.add(0, 1, 1, "set Overlay");
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.drawable.home_menu, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
if(overlay_status==false)
{
menu.findItem(1).setVisible(false);
menu.findItem(0).setVisible(true);
//overlay_status=true;
}
else
{
menu.findItem(0).setVisible(false);
menu.findItem(1).setVisible(true);
// overlay_status=false;
}
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.home1:
finish();
return true;
case 0:
//Toast.makeText(getApplicationContext(), "remove overlay ", Toast.LENGTH_SHORT).show();
// example hiding balloon before removing overlay
if (itemizedOverlay.getFocus() != null) {
itemizedOverlay.hideBalloon();
}
mapOverlays.remove(itemizedOverlay);
mapView.invalidate();
overlay_status=true;
return true;
case 1:
Toast.makeText(getApplicationContext(), "set overlay ", Toast.LENGTH_SHORT).show();
if (itemizedOverlay.getFocus() != null) {
itemizedOverlay.getBalloonBottomOffset();
}
mapOverlays.add(itemizedOverlay);
mapView.bringToFront();
overlay_status=false;
return true;
default:
return super.onOptionsItemSelected(item);
}
}
class Touchy extends Overlay{
List<Address> address;
String display = "";
String display1;
#SuppressWarnings({ "deprecation" })
public boolean onTouchEvent(MotionEvent e,MapView m){
if(e.getAction() == MotionEvent.ACTION_DOWN){
start = e.getEventTime();
x = (int)e.getX();
y = (int)e.getY();
touchedPoint = mapView.getProjection().fromPixels(x, y);
Geocoder geocoder = new Geocoder(getBaseContext(), Locale.getDefault());
try{
address = geocoder.getFromLocation(touchedPoint.getLatitudeE6() / 1E6, touchedPoint.getLongitudeE6() / 1E6, 1);
if(address.size() > 0){
for(int i = 0; i<address.get(0).getMaxAddressLineIndex(); i++){
display +=address.get(0).getAddressLine(i) + "\n";
}
Toast.makeText(getBaseContext(), display, Toast.LENGTH_LONG).show();
}
}catch(IOException e1){
}
finally
{
display1=display;
display=" ";
}
}
if(e.getAction() == MotionEvent.ACTION_UP){
stop = e.getEventTime();
}
/**contains the creating a Alert Dialog Box (place apinpoint, get address, Toggle View)
* In Dialog Box Maximum three buttens
*/
if(stop - start > 1000){
AlertDialog alert = new AlertDialog.Builder(CustomMap.this).create();
alert.setTitle("pick an Option");
alert.setMessage("I told to pick an option");
alert.setButton("place a pinpoint", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
CustomOverlayItem overlayItem = new CustomOverlayItem(touchedPoint,"Address:",display1, display1);
// SimpleItemizedOverlay itemizedOverlay = new SimpleItemizedOverlay(drawable, mapView);
CustomItemizedOverlay<CustomOverlayItem> itemOverlay = new CustomItemizedOverlay<CustomOverlayItem>(drawable, mapView);
// CustomPinpoint custom = new CustomPinpoint(drawable, CustomMap.this);
// custom.insertPinpoint(overlayItem);
itemOverlay.insertPinpoint(overlayItem);
itemOverlay.addOverlay(overlayItem);
mapOverlays.add(itemOverlay);
}
});
alert.setButton2("get address", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Geocoder geocoder = new Geocoder(getBaseContext(), Locale.getDefault());
try{
List<Address> address = geocoder.getFromLocation(touchedPoint.getLatitudeE6() / 1E6, touchedPoint.getLongitudeE6() / 1E6, 1);
if(address.size() > 0){
String display = "";
for(int i = 0; i<address.get(0).getMaxAddressLineIndex(); i++){
display +=address.get(0).getAddressLine(i) + "\n";
}
Toast.makeText(getBaseContext(), display, Toast.LENGTH_LONG).show();
}
}catch(IOException e){
}
}
});
alert.setButton3("Toggle View", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(mapView.isSatellite()){
mapView.setSatellite(false);
mapView.setStreetView(true);
}else{
mapView.setStreetView(false);
mapView.setSatellite(true);
}
}
});
alert.show();
return true;
}
return false;
}
}
#Override
public void onLocationChanged(Location location) {
lati = (int) (location.getLatitude() * 1E6);
longit = (int) (location.getLongitude() * 1E6);
GeoPoint ourLocation = new GeoPoint(lati, longit);
OverlayItem overlayItem = new OverlayItem(ourLocation, "What's up?", "2nd String");
CustomPinpoint custom = new CustomPinpoint(drawable, CustomMap.this);
custom.insertPinpoint(overlayItem);
mapOverlays.add(custom);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
Try this AndroidHive Google code
Google Map Link Android Working with Google Places and Maps Tutorial
public class SinglePlaceActivity extends Activity {
// flag for Internet connection status
Boolean isInternetPresent = false;
// Connection detector class
ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
// Google Places
GooglePlaces googlePlaces;
// Place Details
PlaceDetails placeDetails;
// Progress dialog
ProgressDialog pDialog;
// KEY Strings
public static String KEY_REFERENCE = "reference"; // id of the place
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.single_place);
Intent i = getIntent();
// Place referece id
String reference = i.getStringExtra(KEY_REFERENCE);
// Calling a Async Background thread
new LoadSinglePlaceDetails().execute(reference);
}
/**
* Background Async Task to Load Google places
* */
class LoadSinglePlaceDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SinglePlaceActivity.this);
pDialog.setMessage("Loading profile ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Profile JSON
* */
protected String doInBackground(String... args) {
String reference = args[0];
// creating Places class object
googlePlaces = new GooglePlaces();
// Check if used is connected to Internet
try {
placeDetails = googlePlaces.getPlaceDetails(reference);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed Places into LISTVIEW
* */
if(placeDetails != null){
String status = placeDetails.status;
// check place deatils status
// Check for all possible status
if(status.equals("OK")){
if (placeDetails.result != null) {
String name = placeDetails.result.name;
String address = placeDetails.result.formatted_address;
String phone = placeDetails.result.formatted_phone_number;
String latitude = Double.toString(placeDetails.result.geometry.location.lat);
String longitude = Double.toString(placeDetails.result.geometry.location.lng);
Log.d("Place ", name + address + phone + latitude + longitude);
// Displaying all the details in the view
// single_place.xml
TextView lbl_name = (TextView) findViewById(R.id.name);
TextView lbl_address = (TextView) findViewById(R.id.address);
TextView lbl_phone = (TextView) findViewById(R.id.phone);
TextView lbl_location = (TextView) findViewById(R.id.location);
// Check for null data from google
// Sometimes place details might missing
name = name == null ? "Not present" : name; // if name is null display as "Not present"
address = address == null ? "Not present" : address;
phone = phone == null ? "Not present" : phone;
latitude = latitude == null ? "Not present" : latitude;
longitude = longitude == null ? "Not present" : longitude;
lbl_name.setText(name);
lbl_address.setText(address);
lbl_phone.setText(Html.fromHtml("<b>Phone:</b> " + phone));
lbl_location.setText(Html.fromHtml("<b>Latitude:</b> " + latitude + ", <b>Longitude:</b> " + longitude));
}
}
else if(status.equals("ZERO_RESULTS")){
alert.showAlertDialog(SinglePlaceActivity.this, "Near Places",
"Sorry no place found.",
false);
}
else if(status.equals("UNKNOWN_ERROR"))
{
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry unknown error occured.",
false);
}
else if(status.equals("OVER_QUERY_LIMIT"))
{
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry query limit to google places is reached",
false);
}
else if(status.equals("REQUEST_DENIED"))
{
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry error occured. Request is denied",
false);
}
else if(status.equals("INVALID_REQUEST"))
{
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry error occured. Invalid Request",
false);
}
else
{
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry error occured.",
false);
}
}else{
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry error occured.",
false);
}
}
});
}
}
}
Try this,
mapView.getOverlays().add(locationoverlay);
locationoverlay.runOnFirstFix(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
mapView.getOverlays().add(locationoverlay);
}
});
locationoverlay.enableMyLocation();
mapView.postInvalidate();
Above code will provide the current location in android default marker overlay

How to pass the latitude and longitude of a place to be displayed on google map?

Hi I have developed an android app which uses google places api to display the nearby locations.
Now when I click on a place name I want to display its location in the map. My question is that how to pass the latitude and longitude to the google maps to be displayed. Right now I am passing the values statically but when I click on the name I want to pass its lat and long dynamically to be drawn. Please tell me how to do that. I am new to android.
public class SinglePlaceActivity extends Activity {
// flag for Internet connection status
Boolean isInternetPresent = false;
// Connection detector class
ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
// Google Places
GooglePlaces googlePlaces;
// Place Details
PlaceDetails placeDetails;
// Progress dialog
ProgressDialog pDialog;
Button submit;
Button piechart;
TextView error;
// KEY Strings
public static String KEY_REFERENCE = "reference"; // id of the place
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.single_place);
Intent i = getIntent();
// Place referece id
String reference = i.getStringExtra(KEY_REFERENCE);
// Calling a Async Background thread
new LoadSinglePlaceDetails().execute(reference);
submit = (Button) findViewById(R.id.submitbutton);
piechart = (Button) findViewById(R.id.piechart);
error = (TextView) findViewById(R.id.list);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(SinglePlaceActivity.this,RecoProd.class);
SinglePlaceActivity.this.startActivity(myIntent);
}
});
piechart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myInt = new Intent(SinglePlaceActivity.this,PieChart.class);
SinglePlaceActivity.this.startActivity(myInt);
}
});
}
/**
* Background Async Task to Load Google places
* */
class LoadSinglePlaceDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SinglePlaceActivity.this);
pDialog.setMessage("Loading profile ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Profile JSON
* */
protected String doInBackground(String... args) {
String reference = args[0];
// creating Places class object
googlePlaces = new GooglePlaces();
// Check if used is connected to Internet
try {
placeDetails = googlePlaces.getPlaceDetails(reference);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed Places into LISTVIEW
* */
if(placeDetails != null){
String status = placeDetails.status;
// check place deatils status
// Check for all possible status
if(status.equals("OK")){
if (placeDetails.result != null) {
String name = placeDetails.result.name;
String address = placeDetails.result.formatted_address;
String phone = placeDetails.result.formatted_phone_number;
String website = placeDetails.result.formatted_web_site;
String latitude = Double.toString(placeDetails.result.geometry.location.lat);
String longitude = Double.toString(placeDetails.result.geometry.location.lng);
Log.d("Place ", name + address + phone + latitude + longitude + website);
// Displaying all the details in the view
// single_place.xml
TextView lbl_name = (TextView) findViewById(R.id.name);
TextView lbl_address = (TextView) findViewById(R.id.address);
TextView lbl_phone = (TextView) findViewById(R.id.phone);
TextView lbl_website = (TextView) findViewById(R.id.web_site);
TextView lbl_location = (TextView) findViewById(R.id.location);
lbl_name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(SinglePlaceActivity.this,DispMap.class);
myIntent.putExtra("latitude", "latitude");
myIntent.putExtra("longitude", "longitude");
SinglePlaceActivity.this.startActivity(myIntent);
}
});
// Check for null data from google
// Sometimes place details might missing
name = name == null ? "Not present" : name; // if name is null display as "Not present"
address = address == null ? "Not present" : address;
phone = phone == null ? "Not present" : phone;
website = website == null ? "Not present" : website;
latitude = latitude == null ? "Not present" : latitude;
longitude = longitude == null ? "Not present" : longitude;
lbl_name.setText(name);
lbl_address.setText(address);
lbl_phone.setText(Html.fromHtml("<b>Phone:</b> " + phone));
lbl_website.setText(Html.fromHtml("<b>website:</b> " + website));
lbl_location.setText(Html.fromHtml("<b>Latitude:</b> " + latitude + ", <b>Longitude:</b> " + longitude));
}
}
else if(status.equals("ZERO_RESULTS")){
alert.showAlertDialog(SinglePlaceActivity.this, "Near Places",
"Sorry no place found.",
false);
}
else if(status.equals("UNKNOWN_ERROR"))
{
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry unknown error occured.",
false);
}
else if(status.equals("OVER_QUERY_LIMIT"))
{
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry query limit to google places is reached",
false);
}
else if(status.equals("REQUEST_DENIED"))
{
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry error occured. Request is denied",
false);
}
else if(status.equals("INVALID_REQUEST"))
{
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry error occured. Invalid Request",
false);
}
else
{
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry error occured.",
false);
}
}else{
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry error occured.",
false);
}
}
});
}
}
}
DispMap.Class
MapView mapView;
MapController mc;
GeoPoint p;
String longitude,latitude;
public class MapOverlay extends com.google.android.maps.Overlay
{
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
// TODO Auto-generated method stub
super.draw(canvas, mapView, shadow, when);
//translate the geo points to screen pixels
Point screenPts = new Point();
mapView.getProjection().toPixels(p, screenPts);
//add the marker
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.hospitalbuilding);
Bitmap bmp1 = BitmapFactory.decodeResource(getResources(), R.drawable.shadow);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50,null);
canvas.drawBitmap(bmp1, screenPts.x, screenPts.y-40,null);
return true;
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nearbyhospitals);
//database work
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String hospital_name = extras.getString("Hname");
Toast.makeText(getApplicationContext(), hospital_name, Toast.LENGTH_LONG).show();
// fill the lat and long postion here from database or from elsewhere
longitude = "31.44";
latitude = "75.23";
mapView = (MapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(true);
mc = mapView.getController();
String temp = getCurrentLocation();
try {
} catch (Exception e) {
// TODO: handle exception
}
Toast.makeText(getApplicationContext(), "So here we get:"+latitude+","+longitude, Toast.LENGTH_LONG).show();
String coordinates[] ={"31","71"};
//Toast.makeText(getApplicationContext(), coordinates[0]+","+coordinates[1], Toast.LENGTH_LONG).show();
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);
p = new GeoPoint((int)(lat*1E6), (int)(lng*1E6));
mc.animateTo(p);
mc.setZoom(13);
//---Add a location marker---
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
public String getCurrentLocation()
{
double latitude, longitude;
LocationManager locManager;
locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000L,500.0f, locationListener);
Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null)
{
latitude = location.getLatitude();
longitude = location.getLongitude();
return Double.toString(latitude)+","+Double.toString(longitude);
}
else
return "Location not found please try again";
}
public final LocationListener locationListener = new LocationListener()
{
public void onLocationChanged(Location location)
{
}
public void onProviderDisabled(String provider)
{
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
Try this one:
Add itemizedOverlay class:
public class AndroidGoogleMapsActivity extends MapActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Displaying Zooming controls
MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
MapController mc = mapView.getController();
double lat = Double.parseDouble("48.85827758964043");
double lon = Double.parseDouble("2.294543981552124");
GeoPoint geoPoint = new GeoPoint((int)(lat * 1E6), (int)(lon * 1E6));
mc.animateTo(geoPoint);
mc.setZoom(15);
mapView.invalidate();
/**
* Placing Marker
* */
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.mark_red);
AddItemizedOverlay itemizedOverlay =
new AddItemizedOverlay(drawable, this);
OverlayItem overlayitem = new OverlayItem(geoPoint, "Hello", "Sample Overlay item");
itemizedOverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedOverlay);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
}

how show own location from a address use LocationOverlay?

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);
}
}

Why is location listener function not executing?

// here is my code of MapActivity class
public class MapActivity extends com.google.android.maps.MapActivity implements LocationListener
{
MapView mapView;
MapController mc;
GeoPoint p;
MyLocation myLocation = new MyLocation();
LocationManager mlocManager;
int distance;
public void onCreate(Bundle savedInstanceState) {
// Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
ImageButton mpl = (ImageButton)findViewById(R.id.nearbybuttn);
mapView = (MapView) findViewById(R.id.mv);
mapView.setBuiltInZoomControls(true);
mapView.displayZoomControls(true);
mc = mapView.getController();
mc.setZoom(8);
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 200,
0, mlocListener);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
// gets current location on position change
loc.getLatitude();
loc.getLongitude();
Double slat = loc.getLatitude();
Double slon = loc.getLongitude();
TextView txlat = (TextView) findViewById(R.id.lat);
TextView txlon = (TextView) findViewById(R.id.lon);
txlat.setText(slat + "n");
txlon.setText(slon + "n");
// json retrieval
JSONObject j2 = JSONfunctions
.getJSONfromURL("/merchant/apis/?device=iphone&api=store_details");
try {
JSONArray myID = j2.getJSONArray("stores");
for (int i = 0; i < myID.length(); i++) {
Log.v("state", "json address being read");
JSONObject j3 = myID.getJSONObject(i);
String name = j3.getString("Address");
String id = j3.getString("StoreId");
Log.v("id", id);
Log.v("Address", name);
JSONObject j4 = j3.getJSONObject("Address");
Double jlat = j4.getDouble("Latitude");
Double jlon = j4.getDouble("Longitude");
Log.v("Latitude", jlat + "n");
Log.v("Longitude", jlon + "n");
// Get the distance between lat long
Location locationA = new Location("point A");
locationA.setLatitude(slat);
locationA.setLongitude(slon);
Location locationB = new Location("point B");
locationB.setLatitude(jlat);
locationB.setLongitude(jlon);
distance = (int) locationA.distanceTo(locationB);
String str = " (" + String.valueOf(distance) + " meters)";
Log.v("Distance", str);
// adjust drawable params
Drawable marker = getResources().getDrawable(
android.R.drawable.star_big_on);
Drawable user = getResources().getDrawable(
android.R.drawable.arrow_down_float);
int userWidth = user.getIntrinsicWidth();
int userHeight = user.getIntrinsicHeight();
user.setBounds(0, userHeight, userWidth, 0);
int markerWidth = marker.getIntrinsicWidth();
int markerHeight = marker.getIntrinsicHeight();
marker.setBounds(0, markerHeight, markerWidth, 0);
// refernc to overlay class
LocationOverlay myItemizedOverlay = new LocationOverlay(
marker, MapActivity.this);
LocationOverlay myItemizedOverlay1 = new LocationOverlay(
user, MapActivity.this);
mapView.getOverlays().add(myItemizedOverlay);
mapView.getOverlays().add(myItemizedOverlay1);
// create geopoint for user
GeoPoint usr = new GeoPoint((int) (slat * 1e6),
(int) (slon * 1e6));
// add overlay(user) to user's location
myItemizedOverlay1.addItem(usr, "User");
mc.animateTo(usr);
// create geopoint for json
GeoPoint jgpt = new GeoPoint((int) (jlat * 1e6),
(int) (jlon * 1e6));
// add marker on geopoints from json
myItemizedOverlay.addItem(jgpt, "StoreId" + id);
mapView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return false;
}
});
}
} catch (JSONException e) {
Log.e("loG_tag", "Error parsing" + e.toString());
}
}
private TextView findViewById(int lat) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Disabled",
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Enabled",
Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
}
Not Executing - What should we consider this as a Compile Time or a Runtime Error.
If yes paste the error logs. Also
Are You Trying this on Real Device ? If not do so
Is GPS of your device is ON ? if not do so
Try using 0 parameter instead of 200. See its results.
Also try LocationManager.NETWORK_PROVIDER
Make Sure You have sufficient permission defined in Manifest File.

User pin point location on map and fetch the location's address back to a textbox

I have this textbox in the other activity and a button which leads to this map. What i want to do is that it allows the user to click the map and pin point the location they wants, and they can also fetch that location's address back to the textbox without typing. Can it be done so? Since now there is this alert dialog box which pop up after user pin point it with 2 buttons(Yes and No) So if yes, fetch that location address back to the textbox. Any idea?
static EditText txtLocation;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mapview);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mc = mapView.getController();
List<Overlay> mapOverlays = mapView.getOverlays();
MapOverlay mapOverlay = new MapOverlay();
mapOverlays.add(mapOverlay);
// obtain gps location
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
lm.requestLocationUpdates(
// LocationManager.GPS_PROVIDER,
LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location loc) {
if (loc != null) {
Toast.makeText(
getBaseContext(),
"Location changed: Lat: " + loc.getLatitude()
+ " Lng: " + loc.getLongitude(),
Toast.LENGTH_SHORT).show();
}
p = new GeoPoint((int) (loc.getLatitude() * 1E6),
(int) (loc.getLongitude() * 1E6));
mc.animateTo(p);
mc.setZoom(18);
// Add a location marker
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listofOverlays = mapView.getOverlays();
listofOverlays.clear();
listofOverlays.add(mapOverlay);
// invalidate() method forces the MapView to be redrawn
mapView.invalidate();
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
class MapOverlay extends com.google.android.maps.Overlay {
#Override
public boolean onTap(final GeoPoint p, MapView mapView) {
// TODO Auto-generated method stub
k = p;
mc = mapView.getController();
mc.animateTo(p);
mapView.invalidate();
Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
try{
List<Address> addresses = geoCoder.getFromLocation(
p.getLatitudeE6() /1E6,
p.getLongitudeE6() / 1E6, 1
);
String add = "";
if (addresses.size()>0)
{
for (int i=0; i<addresses.get(0).getMaxAddressLineIndex(); i++)
add += addresses.get(0).getAddressLine(i) + "\n";
}
// txtLocation.setText(add);
Toast.makeText(getBaseContext(), add, Toast.LENGTH_SHORT).show();
}
catch (IOException e){
e.printStackTrace();
}
new AlertDialog.Builder(MapsActivity.this)
.setTitle("Change location..")
.setMessage("go to the new location?")
.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
})
.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
try{
List<Address> addresses = geoCoder.getFromLocation(
p.getLatitudeE6() /1E6,
p.getLongitudeE6() / 1E6, 1
);
String add = "";
if (addresses.size()>0)
{
for (int i=0; i<addresses.get(0).getMaxAddressLineIndex(); i++)
add += addresses.get(0).getAddressLine(i) + "\n";
}
txtLocation.setText(add);
// Toast.makeText(getBaseContext(), add, Toast.LENGTH_SHORT).show();
}
catch (IOException e){
e.printStackTrace();
}
}
}).show();
return true;
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
super.draw(canvas, mapView, shadow);
if (k != null) {
// ---translate the GeoPoint to screen pixels---
Point screenPts = new Point();
mapView.getProjection().toPixels(k, screenPts);
// ---add the marker---
Bitmap bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.marker);
canvas.drawBitmap(bmp, screenPts.x - 10, screenPts.y - 34, null);
}
return true;
}
}
}
Well you can try reverse geocoding. What that needs is you to supply the lat long of the point that the user tapped on, which is fairly easy.
Check this similar question. might help.

Categories

Resources