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
Related
I followed a tutorial from;
http://www.androidhive.info/2012/08/android-working-with-google-places-and-maps-tutorial/
The google places aspect works perfect but the google map code is outdated. Im not sure how to update google map code from v1 to v2?
Any pointers??
public class PlacesMapActivity extends MapActivity {
// Nearest places
PlacesList nearPlaces;
// Map view
MapView mapView;
// Map overlay items
List<Overlay> mapOverlays;
AddItemizedOverlay itemizedOverlay;
GeoPoint geoPoint;
// Map controllers
MapController mc;
double latitude;
double longitude;
OverlayItem overlayitem;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_places);
// Getting intent data
Intent i = getIntent();
// Users current geo location
String user_latitude = i.getStringExtra("user_latitude");
String user_longitude = i.getStringExtra("user_longitude");
// Nearplaces list
nearPlaces = (PlacesList) i.getSerializableExtra("near_places");
mapView = (MapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mapOverlays = mapView.getOverlays();
// Geopoint to place on map
geoPoint = new GeoPoint((int) (Double.parseDouble(user_latitude) * 1E6),
(int) (Double.parseDouble(user_longitude) * 1E6));
// Drawable marker icon
Drawable drawable_user = this.getResources()
.getDrawable(R.drawable.mark_red);
itemizedOverlay = new AddItemizedOverlay(drawable_user, this);
// Map overlay item
overlayitem = new OverlayItem(geoPoint, "Your Location",
"That is you!");
itemizedOverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedOverlay);
itemizedOverlay.populateNow();
// Drawable marker icon
Drawable drawable = this.getResources()
.getDrawable(R.drawable.mark_blue);
itemizedOverlay = new AddItemizedOverlay(drawable, this);
mc = mapView.getController();
// These values are used to get map boundary area
// The area where you can see all the markers on screen
int minLat = Integer.MAX_VALUE;
int minLong = Integer.MAX_VALUE;
int maxLat = Integer.MIN_VALUE;
int maxLong = Integer.MIN_VALUE;
// check for null in case it is null
if (nearPlaces.results != null) {
// loop through all the places
for (Place place : nearPlaces.results) {
latitude = place.geometry.location.lat; // latitude
longitude = place.geometry.location.lng; // longitude
// Geopoint to place on map
geoPoint = new GeoPoint((int) (latitude * 1E6),
(int) (longitude * 1E6));
// Map overlay item
overlayitem = new OverlayItem(geoPoint, place.name,
place.vicinity);
itemizedOverlay.addOverlay(overlayitem);
// calculating map boundary area
minLat = (int) Math.min( geoPoint.getLatitudeE6(), minLat );
minLong = (int) Math.min( geoPoint.getLongitudeE6(), minLong);
maxLat = (int) Math.max( geoPoint.getLatitudeE6(), maxLat );
maxLong = (int) Math.max( geoPoint.getLongitudeE6(), maxLong );
}
mapOverlays.add(itemizedOverlay);
// showing all overlay items
itemizedOverlay.populateNow();
}
// Adjusting the zoom level so that you can see all the markers on map
mapView.getController().zoomToSpan(Math.abs( minLat - maxLat ), Math.abs( minLong - maxLong ));
// Showing the center of the map
mc.animateTo(new GeoPoint((maxLat + minLat)/2, (maxLong + minLong)/2 ));
mapView.postInvalidate();
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
}
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) {
OverlayItem item = mapOverlays.get(index);
AlertDialog.Builder dialog = new AlertDialog.Builder(this.context);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
dialog.show();
return true;
}
public void addOverlay(OverlayItem overlay) {
mapOverlays.add(overlay);
}
public void populateNow(){
this.populate();
}
}
public class NearbyActivity 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;
// Places List
PlacesList nearPlaces;
// GPS Location
GPSTracker gps;
// Button
Button btnShowOnMap;
// Progress dialog
ProgressDialog pDialog;
// Places Listview
ListView lv;
// ListItems data
ArrayList<HashMap<String, String>> placesListItems = new ArrayList<HashMap<String,String>>();
// KEY Strings
public static String KEY_REFERENCE = "reference"; // id of the place
public static String KEY_NAME = "name"; // name of the place
public static String KEY_VICINITY = "vicinity"; // Place area name
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.main3);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title);
Button buttonNear = (Button) findViewById(R.id.buttonNearby);
buttonNear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
//Starting a new Intent
Intent HomeScreen = new Intent(getApplicationContext(),HomeActivity.class);
startActivity(HomeScreen);
}
});
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
isInternetPresent = cd.isConnectingToInternet();
if (!isInternetPresent) {
// Internet Connection is not present
alert.showAlertDialog(NearbyActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// creating GPS Class object
gps = new GPSTracker(this);
// check if GPS location can get
if (gps.canGetLocation()) {
Log.d("Your Location", "latitude:" + gps.getLatitude() + ", longitude: " + gps.getLongitude());
} else {
// Can't get user's current location
alert.showAlertDialog(NearbyActivity.this, "GPS Status",
"Couldn't get location information. Please enable GPS",
false);
// stop executing code by return
return;
}
// Getting listview
lv = (ListView) findViewById(R.id.list);
// button show on map
btnShowOnMap = (Button) findViewById(R.id.btn_show_map);
// calling background Async task to load Google Places
// After getting places from Google all the data is shown in listview
new LoadPlaces().execute();
/** Button click event for shown on map */
btnShowOnMap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(),
PlacesMapActivity.class);
// Sending user current geo location
i.putExtra("user_latitude", Double.toString(gps.getLatitude()));
i.putExtra("user_longitude", Double.toString(gps.getLongitude()));
// passing near places to map activity
i.putExtra("near_places", nearPlaces);
// staring activity
startActivity(i);
}
});
/**
* ListItem click event
* On selecting a listitem SinglePlaceActivity is launched
* */
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String reference = ((TextView) view.findViewById(R.id.reference)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
SinglePlaceActivity.class);
// Sending place refrence id to single place activity
// place refrence id used to get "Place full details"
in.putExtra(KEY_REFERENCE, reference);
startActivity(in);
}
});
}
/**
* Background Async Task to Load Google places
* */
class LoadPlaces extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NearbyActivity.this);
pDialog.setMessage(Html.fromHtml("<b>Search</b><br/>Loading Places..."));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Places JSON
* */
protected String doInBackground(String... args) {
// creating Places class object
googlePlaces = new GooglePlaces();
try {
// Separeate your place types by PIPE symbol "|"
// If you want all types places make it as null
// Check list of types supported by google
//
String types = null; // Listing places only cafes, restaurants
// Radius in meters - increase this value if you don't find any places
double radius = 400; // 1000 meters
// get nearest places
nearPlaces = googlePlaces.search(gps.getLatitude(),
gps.getLongitude(), radius, types);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* and show the data in UI
* Always use runOnUiThread(new Runnable()) to update UI from background
* thread, otherwise you will get error
* **/
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
* */
// Get json response status
String status = nearPlaces.status;
// Check for all possible status
if(status.equals("OK")){
// Successfully got places details
if (nearPlaces.results != null) {
// loop through each place
for (Place p : nearPlaces.results) {
HashMap<String, String> map = new HashMap<String, String>();
// Place reference won't display in listview - it will be hidden
// Place reference is used to get "place full details"
map.put(KEY_REFERENCE, p.reference);
// Place name
map.put(KEY_NAME, p.name);
// adding HashMap to ArrayList
placesListItems.add(map);
}
// list adapter
ListAdapter adapter = new SimpleAdapter(NearbyActivity.this, placesListItems,
R.layout.list_item,
new String[] { KEY_REFERENCE, KEY_NAME}, new int[] {
R.id.reference, R.id.name });
// Adding data into listview
lv.setAdapter(adapter);
}
}
else if(status.equals("ZERO_RESULTS")){
// Zero results found
alert.showAlertDialog(NearbyActivity.this, "Near Places",
"Sorry no places found. Try to change the types of places",
false);
}
else if(status.equals("UNKNOWN_ERROR"))
{
alert.showAlertDialog(NearbyActivity.this, "Places Error",
"Sorry unknown error occured.",
false);
}
else if(status.equals("OVER_QUERY_LIMIT"))
{
alert.showAlertDialog(NearbyActivity.this, "Places Error",
"Sorry query limit to google places is reached",
false);
}
else if(status.equals("REQUEST_DENIED"))
{
alert.showAlertDialog(NearbyActivity.this, "Places Error",
"Sorry error occured. Request is denied",
false);
}
else if(status.equals("INVALID_REQUEST"))
{
alert.showAlertDialog(NearbyActivity.this, "Places Error",
"Sorry error occured. Invalid Request",
false);
}
else
{
alert.showAlertDialog(NearbyActivity.this, "Places Error",
"Sorry error occured.",
false);
}
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
}
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;
}
}
public class LocateActivity extends MapActivity {
MapView mapView = null;
Geocoder geocoder = null;
Drawable drawable = null;
Geocoder gc = null;
final CountDownLatch signal = new CountDownLatch(1);
String status;
double lat;
double lng;
public ArrayAdapter<String> adapter;
public AutoCompleteTextView filltt;
public static String KEY_REFERENCE = "reference"; // id of the place
public static String KEY_NAME = "name"; // name of the place
public static String KEY_VICINITY = "vicinity"; //
ProgressDialog pDialog;
PlacesList nearPlaces;
List<Overlay> mapOverlays;
AddItemizedOverlay itemizedOverlay;
GeoPoint geoPoint;
// Map controllers
MapController mc;
double latitude;
double longitude;
OverlayItem overlayitem;
Drawable drawable_user;
Drawable drawablee;
String locnm;
GPSTracker gps;
GooglePlaces googlePlaces;
ArrayList<HashMap<String, String>> placesListItems = new ArrayList<HashMap<String,String>>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
System.out.println("My locale::"+Locale.getDefault().getDisplayLanguage());
filltt = (AutoCompleteTextView)findViewById(id.autoCompleteTextView1);
mapView = (MapView) findViewById(R.id.geoMap);
mapView.setBuiltInZoomControls(true);
mapView.setClickable(true);
mapOverlays = mapView.getOverlays();
gc = new Geocoder(this);
drawable = this.getResources().getDrawable(R.drawable.pon);
adapter = new ArrayAdapter<String>(this,R.layout.item_list);
adapter.setNotifyOnChange(true);
filltt.setAdapter(adapter);
filltt.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (count%3 == 1) {
adapter.clear();
GetPlaces task = new GetPlaces();
//now pass the argument in the textview to the task
task.execute(filltt.getText().toString());
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
public void afterTextChanged(Editable s) {
}
});
// map starting point
int lat = (int) (51.678383 * 1000000);
int lng = (int) (19.334822 * 1000000);
GeoPoint pt = new GeoPoint(lat, lng);
mapView.getController().setZoom(18);
mapView.getController().setCenter(pt);
final String lattt="23.0666";
final String loggg="72.6666";
Button geoBtn = (Button) findViewById(R.id.geocodeBtn);
// geoBtn.setText(Html.fromHtml("<b>Year:</b>2012,<b>Franch</b>"));
geocoder = new Geocoder(this);
geoBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
locnm = filltt.getText().toString();
if(locnm.length()==0){
Toast.makeText(LocateActivity.this, "Enter Location", Toast.LENGTH_LONG).show();
}
else
// EditText locale = (EditText) findViewById(R.id.location);
{
new LoadPlaces().execute();
String locationName = filltt.getText().toString();
Toast.makeText(LocateActivity.this, locationName, Toast.LENGTH_LONG).show();
System.out.println("location: "+locationName);
List<Address> addressList = geocoder.getFromLocationName(
locationName, 5);
System.out.println("first val: " + addressList.get(0));
System.out.println("Total Result: " + addressList.size());
if (addressList != null && addressList.size() > 0) {
int lat = (int) (addressList.get(0).getLatitude() * 1e6);
int lng = (int) (addressList.get(0).getLongitude() * 1e6);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// refresh your views here
super.onConfigurationChanged(newConfig);
}
class GetPlaces extends AsyncTask<String, Void, ArrayList<String>>
{
#Override
// three dots is java for an array of strings
protected ArrayList<String> doInBackground(String... args)
{
Log.d("gottaGo", "doInBackground");
ArrayList<String> predictionsArr = new ArrayList<String>();
try
{
URL googlePlaces = new URL(
// URLEncoder.encode(url,"UTF-8");
"https://maps.googleapis.com/maps/api/place/autocomplete/json?input="+ URLEncoder.encode(args[0].toString(), "UTF-8") +"&types=geocode&language=en&sensor=true&key=AIzaSyDYnuaL0x_7xGNqrEvYkgEB20_k-b4avOI");
URLConnection tc = googlePlaces.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
String line;
StringBuffer sb = new StringBuffer();
//take Google's legible JSON and turn it into one big string.
while ((line = in.readLine()) != null) {
sb.append(line);
System.out.println("Line: "+line);
}
//turn that string into a JSON object
JSONObject predictions = new JSONObject(sb.toString());
//now get the JSON array that's inside that object
JSONArray ja = new JSONArray(predictions.getString("predictions"));
System.out.println(ja.length());
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
//add each entry to our array
predictionsArr.add(jo.getString("description"));
}
} catch (IOException e){
Log.e("YourApp", "GetPlaces : doInBackground", e);
} catch (JSONException e){
Log.e("YourApp", "GetPlaces : doInBackground", e);
}
return predictionsArr;
}
//then our post
#Override
protected void onPostExecute(ArrayList<String> result)
{
Log.d("YourApp", "onPostExecute : " + result.size());
//update the adapter
adapter = new ArrayAdapter<String>(getBaseContext(), R.layout.item_list);
adapter.setNotifyOnChange(true);
//attach the adapter to textview
filltt.setAdapter(adapter);
for (String string : result)
{
Log.d("YourApp", "onPostExecute : result = " + string);
adapter.add(string);
adapter.notifyDataSetChanged();
}
Log.d("YourApp", "onPostExecute : autoCompleteAdapter" + adapter.getCount());
}
}
class LoadPlaces extends AsyncTask<String, String, PlacesList> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LocateActivity.this);
pDialog.setMessage(Html.fromHtml("<b>Search</b><br/>Loading Places..."));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Places JSON
* */
#SuppressLint("NewApi")
protected PlacesList doInBackground(String... args) {
// creating Places class object
googlePlaces = new GooglePlaces();
try {
if(gc.isPresent()){
List<Address> list = gc.getFromLocationName(locnm, 1);
Address address = list.get(0);
lat = address.getLatitude();
lng = address.getLongitude();
}
System.out.println("Lat Val: " + lat);
System.out.println("Long Val: " + lng);
String types = ""; // Listing places only cafes, restaurants
// Radius in meters - increase this value if you don't find any places
double radius = 1000; // 1000 meters
// get nearest places
nearPlaces = googlePlaces.search(lat,
lng, radius, types);
System.out.println("Places: "+nearPlaces);
// }
} catch (Exception e) {
e.printStackTrace();
}
return nearPlaces;
}
/**
* After completing background task Dismiss the progress dialog
* and show the data in UI
* Always use runOnUiThread(new Runnable()) to update UI from background
* thread, otherwise you will get error
* **/
protected void onPostExecute(PlacesList file_url) {
super.onPostExecute(file_url);
// dismiss the dialog after getting all products
pDialog.dismiss();
signal.countDown();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed Places into LISTVIEW
* */
// Get json response status
status = nearPlaces.status;
// Check for all possible status
if(status.equals("OK")){
// Successfully got places details
if (nearPlaces.results != null) {
// loop through each place
for (Place p : nearPlaces.results) {
HashMap<String, String> map = new HashMap<String, String>();
// Place reference won't display in listview - it will be hidden
// Place reference is used to get "place full details"
map.put(KEY_REFERENCE, p.reference);
// Place name
map.put(KEY_NAME, p.name);
System.out.println("Place Name: " +p.name);
// adding HashMap to ArrayList
placesListItems.add(map);
System.out.println("ITEM: " + placesListItems.get(0));
}
}
}
else if(status.equals("ZERO_RESULTS")){
}
else if(status.equals("UNKNOWN_ERROR"))
{
}
else if(status.equals("OVER_QUERY_LIMIT"))
{
}
else if(status.equals("REQUEST_DENIED"))
{
}
else if(status.equals("INVALID_REQUEST"))
{
}
else
{
}
}
});
try {
signal.await(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mapOverlays = mapView.getOverlays();
// Geopoint to place on map
geoPoint = new GeoPoint((int) (lat * 1E6),
(int) (lng * 1E6));
// Drawable marker icon
Drawable drawable_user = getResources()
.getDrawable(R.drawable.mark_red);
itemizedOverlay = new AddItemizedOverlay(drawable_user);
// Map overlay item
overlayitem = new OverlayItem(geoPoint, "Your Location",
"That is you!");
itemizedOverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedOverlay);
itemizedOverlay.populateNow();
// Drawable marker icon
Drawable drawable = getResources()
.getDrawable(R.drawable.mark_blue);
itemizedOverlay = new AddItemizedOverlay(drawable);
mc = mapView.getController();
// These values are used to get map boundary area
// The area where you can see all the markers on screen
int minLat = Integer.MAX_VALUE;
int minLong = Integer.MAX_VALUE;
int maxLat = Integer.MIN_VALUE;
int maxLong = Integer.MIN_VALUE;
// check for null in case it is null
if (nearPlaces.results != null) {
// loop through all the places
for (Place place : nearPlaces.results) {
latitude = place.geometry.location.lat; // latitude
longitude = place.geometry.location.lng; // longitude
// Geopoint to place on map
geoPoint = new GeoPoint((int) (latitude * 1E6),
(int) (longitude * 1E6));
// Map overlay item
overlayitem = new OverlayItem(geoPoint, place.name,
place.vicinity);
itemizedOverlay.addOverlay(overlayitem);
// calculating map boundary area
minLat = (int) Math.min( geoPoint.getLatitudeE6(), minLat );
minLong = (int) Math.min( geoPoint.getLongitudeE6(), minLong);
maxLat = (int) Math.max( geoPoint.getLatitudeE6(), maxLat );
maxLong = (int) Math.max( geoPoint.getLongitudeE6(), maxLong );
}
mapOverlays.add(itemizedOverlay);
// showing all overlay items
itemizedOverlay.populateNow();
}
// Adjusting the zoom level so that you can see all the markers on map
mapView.getController().zoomToSpan(Math.abs( minLat - maxLat ), Math.abs( minLong - maxLong ));
// Showing the center of the map
mc.animateTo(new GeoPoint((maxLat + minLat)/2, (maxLong + minLong)/2 ));
mapView.postInvalidate();
}
}
#Override
public boolean isLocationDisplayed() {
return false;
}
#Override
public boolean isRouteDisplayed() {
return false;
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
exitByBackKey();
//moveTaskToBack(false);
return true;
}
return super.onKeyDown(keyCode, event);
}
protected void exitByBackKey() {
AlertDialog alertbox = new AlertDialog.Builder(this)
.setMessage("Do you really want to Exit ?")
.setPositiveButton("YES", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
filltt.setText("");
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
//close();
}
})
.setNegativeButton("NO", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
}
})
.show();
}
}
Note: this code run perfectly in android 4.0 but when i test it in android 2.3, it gives me force close error. and throws me error like
Service not available.. and latitude and longtitude values are 0.
what is the solution for that? Please, help me to get out of this.
I got the solution.
package com.example.locatebased;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Hashtable;
import org.kxml.*;
import org.kxml.io.*;
import org.kxml.kdom.*;
import org.kxml.parser.*;
import android.util.Log;
public class Geocoding
{
Hashtable ht=null;
private boolean time=true;
private int count=0;
private String citystreetvalue=null;
public Geocoding()
{
System.out.println("Constructor call...");
ht=new Hashtable();
}
//***************************** Find Address of the latitude Longitude ***********
public String parseXml(String address)
{
try
{
System.out.println("Address is:" + address);
//URL mUrl = new URL("http://maps.google.com/maps/api/geocode/xml?address=tagore%20road%20rajkot&sensor=false");
URL mUrl = new URL("http://maps.google.com/maps/api/geocode/xml?address=" + address + "&sensor=false");
Log.e("Url",mUrl.toString());
HttpURLConnection mConn = (HttpURLConnection) mUrl.openConnection();
System.out.println("After address add...");
InputStream is = mConn.getInputStream();
Reader reader = new InputStreamReader(is);
XmlParser parser = new XmlParser(reader);
traverse(parser,"");
mConn.disconnect();
is.close();
System.out.println("Close all connection...");
if(ht.get("status").toString().equals("OK"))
{
System.out.println("result is Ok..." + ht.get("locality").toString() );
citystreetvalue=ht.get("latitude").toString() + ","+ ht.get("longitude").toString() +","+ht.get("locality").toString();
}
else
{
System.out.println("result is not Ok...");
citystreetvalue="InvalidLocation";
}
}
catch(Exception e)
{
System.out.println(e.toString());
}
System.out.println("before returen statement...");
return citystreetvalue;
}
public void traverse(XmlParser parser, String indent ) throws Exception
{
System.out.println("in Traverse method....");
boolean leave = false;
String title = new String();
String desc = new String();
do
{
ParseEvent event = parser.read ();
ParseEvent pe;
switch (event.getType())
{
// For example, <title>
case Xml.START_TAG:
// see API doc of StartTag for more access methods
// Pick up Title for display
if ("status".equals(event.getName()))
{
pe = parser.read();
title = pe.getText();
ht.put("status",title);
}
if(count<2)
{
if ("lat".equals(event.getName()))
{
pe = parser.read();
title = pe.getText();
ht.put("latitude",title);
count=count+1;
}
if ("lng".equals(event.getName()))
{
pe = parser.read();
desc = pe.getText();
ht.put("longitude",desc);
count=count+1;
}
}
if ("long_name".equals(event.getName()))
{
pe = parser.read();
title = pe.getText();
}
if ("type".equals(event.getName()))
{
pe = parser.read();
desc = pe.getText();
if(desc.equals("route"))
{
System.out.println("street is:" + title);
ht.put("street",title);
}
}
if("formatted_address".equals(event.getName()))
{
if(time)
{
pe = parser.read();
title = pe.getText();
ht.put("address",title);
time=false;
}
}
ht.put(desc,title);
traverse(parser,"") ; // recursion call for each <tag></tag>
break;
// For example </title?
case Xml.END_TAG:
leave = true;
break;
// For example </rss>
case Xml.END_DOCUMENT:
leave = true;
break;
// For example, the text between tags
case Xml.TEXT:
break;
case Xml.WHITESPACE:
break;
default:
}
} while( !leave );
}
}
now add below code in mainactivity class:
geocoding=new Geocoding();
locnm=locnm.replace(" ","%20");
String citystreetvalue=geocoding.parseXml(locnm);
System.out.println("string is:" + citystreetvalue);
if(citystreetvalue.equals("InvalidLocation"))
{
}else
{
String citystreetval[]=Split(citystreetvalue, ",");
String latstreet=citystreetval[2];
nlatitude=citystreetval[0];
nlongitude=citystreetval[1];
}
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 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.