How to get an address from map in android? - android

I am building an android application where user can select the address as his favorite places from map.
I need is that when any user double tap any place it should be displayed in my text View and it should work in 100% zoom.
Here is my code -
package com.amal.googlemap;
public class MainActivitytut extends FragmentActivity{
GoogleMap map;
private static final LatLng GOLDEN_GATE_BRIDGE =
new LatLng(37.828891,-122.485884);
private static final LatLng APPLE =
new LatLng(37.3325004578, -122.03099823);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maintut);
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
if (map == null) {
Toast.makeText(this, "Google Maps not available",
Toast.LENGTH_LONG).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
// present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_sethybrid:
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
break;
case R.id.menu_showtraffic:
map.setTrafficEnabled(true);
break;
case R.id.menu_zoomin:
map.animateCamera(CameraUpdateFactory.zoomIn());
break;
case R.id.menu_zoomout:
map.animateCamera(CameraUpdateFactory.zoomOut());
break;
case R.id.menu_gotolocation:
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(GOLDEN_GATE_BRIDGE) // Sets the center of the map to
// Golden Gate Bridge
.zoom(17) // Sets the zoom
.bearing(90) // Sets the orientation of the camera to east
.tilt(30) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
map.animateCamera(CameraUpdateFactory.newCameraPosition(
cameraPosition));
break;
case R.id.menu_addmarker:
// ---using the default marker---
/*
map.addMarker(new MarkerOptions()
.position(GOLDEN_GATE_BRIDGE)
.title("Golden Gate Bridge") .snippet("San Francisco")
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
*/
map.addMarker(new MarkerOptions()
.position(GOLDEN_GATE_BRIDGE)
.title("Golden Gate Bridge")
.snippet("San Francisco")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_launcher)));
break;
case R.id.menu_getcurrentlocation:
// ---get your current location and display a blue dot---
map.setMyLocationEnabled(true);
break;
case R.id.menu_showcurrentlocation:
Location myLocation = map.getMyLocation();
LatLng myLatLng = new LatLng(myLocation.getLatitude(),
myLocation.getLongitude());
CameraPosition myPosition = new CameraPosition.Builder()
.target(myLatLng).zoom(17).bearing(90).tilt(30).build();
map.animateCamera(
CameraUpdateFactory.newCameraPosition(myPosition));
break;
case R.id.menu_lineconnecttwopoints:
//---add a marker at Apple---
map.addMarker(new MarkerOptions()
.position(APPLE)
.title("Apple")
.snippet("Cupertino")
.icon(BitmapDescriptorFactory.defaultMarker(
BitmapDescriptorFactory.HUE_AZURE)));
//---draw a line connecting Apple and Golden Gate Bridge---
map.addPolyline(new PolylineOptions()
.add(GOLDEN_GATE_BRIDGE, APPLE).width(5).color(Color.RED));
break;
}
return true;
}
}
I had tried many method but nothing worked as what I need....
Please help..

try this may help you,
Address address = getAddressFromLatLong(context,lat,long);
public static Address getAddressFromLatLong(Context context,double lat, double lng) {
geocoder = new Geocoder(context);
List<Address> list = null;
try {
list = geocoder.getFromLocation(lat, lng, 10);
return list.get(0);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}

At first set a OnMapClickListener to the Map.
googleMap.setOnMapClickListener(new OnMapClickListener(){
void onMapClick(LatLng point){
Location location = new Location("Test");
location.setLatitude(point.latitude);
location.setLongitude(point.longitude);
(new GetAddressTask(this)).execute(point);
}
});
The GetAddressTask is described here:
https://developer.android.com/training/location/display-address.html#DefineTask
Here is a excerpt of this:
protected class GetAddressTask extends AsyncTask<Location, Void, String> {
Context localContext;
public GetAddressTask(Context context) {
super();
localContext = context;
}
#Override
protected String doInBackground(Location... params) {
Geocoder geocoder = new Geocoder(localContext, Locale.getDefault());
Location location = params[0];
List <Address> addresses = null;
try {
addresses = geocoder.getFromLocation(location.getLatitude(),
location.getLongitude(), 1);
} catch (Exception exception) {
return "Error Message";
}
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String addressText = ((address.getMaxAddressLineIndex() > 0) ?
address.getAddressLine(0) : "") + ", " +
address.getLocality() + ", " +
address.getCountryName();
return addressText;
} else {
return getString(R.string.no_address_found);
}
}
#Override
protected void onPostExecute(String address) {
textView.setText(address);
}
}
For compatibility to Android Developers example i have simply convert the LatLng object to a Location. To remove this conversion you should extend the GetAddressTask class from AsyncTask<LatLng, Void, String> and adapt to doInBackground(LatLng... latlngs) and the `` to geocoder.getFromLocation(latlng.latitude, latlng.longitude, 1);

To get Physical address from LAT LONG try this link-
http://android-er.blogspot.in/2011/02/get-address-from-location-using.html
To Get LAT LONG on touch event:-
how to get lat and long on touch event from google map?
First tap on Google map and get the lat long then use the geocoder to convert LatLong to Physical Address.

Related

Android Google Map how to check if the gps location is inside the circle

I'm trying to detect if a user is in the radius of a Marker , using the users gps location. I have the marker's coordinates, but I don't know how to calculate whether the user is in the area. I've tried to use the following, but even when the current location is inside the circle I keep getting the "outside" message.
public class MapaEscola extends FragmentActivity {
private GoogleMap googleMap;
private Serializable escolas;
private ProgressDialog dialog;
private Circle mCircle;
private Marker mMarker;
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
setContentView(R.layout.maps);
// Loading map
initilizeMap();
// Changing map type
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// Showing / hiding your current location
googleMap.setMyLocationEnabled(true);
// Enable / Disable zooming controls
googleMap.getUiSettings().setZoomControlsEnabled(true);
// Enable / Disable my location button
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
// Enable / Disable Compass icon
googleMap.getUiSettings().setCompassEnabled(true);
// Enable / Disable Rotate gesture
googleMap.getUiSettings().setRotateGesturesEnabled(true);
// Enable / Disable zooming functionality
googleMap.getUiSettings().setZoomGesturesEnabled(true);
Bundle extra = getIntent().getBundleExtra("extra");
ArrayList<Escolas> objects = (ArrayList<Escolas>) extra.getSerializable("array");
try {
for(int i = 0; i < objects.size(); i ++) {
System.out.println(" escolas " + objects.get(i).getLatitude() + " " + objects.get(i).getLongitude());
float latitude = objects.get(i).getLatitude();
float longitude = objects.get(i).getLongitude();
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-23.316281, -51.155528), 15));
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(new LatLng(latitude, longitude));
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
LatLng latLng = new LatLng(latitude, longitude);
drawMarkerWithCircle(latLng);
googleMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
float[] distance = new float[2];
Location.distanceBetween( mMarker.getPosition().latitude, mMarker.getPosition().longitude,
mCircle.getCenter().latitude, mCircle.getCenter().longitude, distance);
if( distance[0] > (mCircle.getRadius() / 2) ){
Toast.makeText(getBaseContext(), "Outside", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "Inside", Toast.LENGTH_LONG).show();
}
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void drawMarkerWithCircle(LatLng position){
double radiusInMeters = 500.0;
int strokeColor = 0xffff0000; //red outline
int shadeColor = 0x44ff0000; //opaque red fill
CircleOptions circleOptions = new CircleOptions().center(position).radius(radiusInMeters).fillColor(shadeColor).strokeColor(strokeColor).strokeWidth(8);
mCircle = googleMap.addCircle(circleOptions);
MarkerOptions markerOptions = new MarkerOptions().position(position);
mMarker = googleMap.addMarker(markerOptions);
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Não foi possível carregar o mapa", Toast.LENGTH_SHORT)
.show();
}
}
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
super.onBackPressed();
finish();
return true;
}
return true;
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
}
I just ran the updated code and figured out what the main problem is.
You should be using the Location passed into the onMyLocationChange() callback, so that it uses your current location to tell if the device is within the circle or not:
googleMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
float[] distance = new float[2];
/*
Location.distanceBetween( mMarker.getPosition().latitude, mMarker.getPosition().longitude,
mCircle.getCenter().latitude, mCircle.getCenter().longitude, distance);
*/
Location.distanceBetween( location.getLatitude(), location.getLongitude(),
mCircle.getCenter().latitude, mCircle.getCenter().longitude, distance);
if( distance[0] > mCircle.getRadius() ){
Toast.makeText(getBaseContext(), "Outside, distance from center: " + distance[0] + " radius: " + mCircle.getRadius(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "Inside, distance from center: " + distance[0] + " radius: " + mCircle.getRadius() , Toast.LENGTH_LONG).show();
}
}
});
Here is the full working example that I ran, it's a pared down version of your original code:
public class MainActivity extends ActionBarActivity {
private GoogleMap googleMap;
private Serializable escolas;
private ProgressDialog dialog;
private Circle mCircle;
private Marker mMarker;
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
setContentView(R.layout.activity_main);
// Loading map
initilizeMap();
// Changing map type
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// Showing / hiding your current location
googleMap.setMyLocationEnabled(true);
// Enable / Disable zooming controls
googleMap.getUiSettings().setZoomControlsEnabled(true);
// Enable / Disable my location button
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
// Enable / Disable Compass icon
googleMap.getUiSettings().setCompassEnabled(true);
// Enable / Disable Rotate gesture
googleMap.getUiSettings().setRotateGesturesEnabled(true);
// Enable / Disable zooming functionality
googleMap.getUiSettings().setZoomGesturesEnabled(true);
// Bundle extra = getIntent().getBundleExtra("extra");
//ArrayList<Escolas> objects = (ArrayList<Escolas>) extra.getSerializable("array");
try {
//test outside
double mLatitude = 37.77657;
double mLongitude = -122.417506;
//test inside
//double mLatitude = 37.7795516;
//double mLongitude = -122.39292;
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLatitude, mLongitude), 15));
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(new LatLng(mLatitude, mLongitude));
//googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
LatLng latLng = new LatLng(mLatitude, mLongitude);
drawMarkerWithCircle(latLng);
googleMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
float[] distance = new float[2];
/*
Location.distanceBetween( mMarker.getPosition().latitude, mMarker.getPosition().longitude,
mCircle.getCenter().latitude, mCircle.getCenter().longitude, distance);
*/
Location.distanceBetween( location.getLatitude(), location.getLongitude(),
mCircle.getCenter().latitude, mCircle.getCenter().longitude, distance);
if( distance[0] > mCircle.getRadius() ){
Toast.makeText(getBaseContext(), "Outside, distance from center: " + distance[0] + " radius: " + mCircle.getRadius(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "Inside, distance from center: " + distance[0] + " radius: " + mCircle.getRadius() , Toast.LENGTH_LONG).show();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
private void drawMarkerWithCircle(LatLng position){
double radiusInMeters = 500.0;
int strokeColor = 0xffff0000; //red outline
int shadeColor = 0x44ff0000; //opaque red fill
CircleOptions circleOptions = new CircleOptions().center(position).radius(radiusInMeters).fillColor(shadeColor).strokeColor(strokeColor).strokeWidth(8);
mCircle = googleMap.addCircle(circleOptions);
MarkerOptions markerOptions = new MarkerOptions().position(position);
mMarker = googleMap.addMarker(markerOptions);
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(
R.id.map)).getMap();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Não foi possível carregar o mapa", Toast.LENGTH_SHORT)
.show();
}
}
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
super.onBackPressed();
finish();
return true;
}
return true;
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
}
Results of Inside the circle:
Results of outside the circle:
#Daniel Nugent:
imho getRadius() will return the radius and not the diameter so the "/2" is wrong
#WARpoluido:
I cant see that the mMarker variable is updated when the location changes. Why dont you use the value given to onMyLocationChange()?
Location.distanceBetween( mCircle.getCenter().latitude, mCircle.getCenter().longitude, location.getLatitude(), location.getLongitude(), distance);
if( distance[0] > mCircle.getRadius() ){
...
Hi I have got mine working correctly with this code
//Getting current location
private void getCurrentLocation() {
mMap.clear();
//Creating a location object
Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (location != null) {
//Getting longitude and latitude
longitude = location.getLongitude();
latitude = location.getLatitude();
//moving the map to location
moveMap();
}
Circle circle = mMap.addCircle(new CircleOptions()
.center(new LatLng(54.773097, -6.557841))
.radius(55)
.strokeColor(Color.RED)
);
pLong = location.getLongitude();
pLat = location.getLatitude();
float[] distance = new float[2];
Location.distanceBetween(pLat, pLong,
circle.getCenter().latitude, circle.getCenter().longitude, distance);
if( distance[0] > circle.getRadius() ){
Toast.makeText(getBaseContext(), "You are not in a bunker", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "You are inside a bunker", Toast.LENGTH_LONG).show();
}
}
Inside the circle
Outside the circle
The accepted solution of Daniel Nugent isn't so good anymore because setOnMyLocationChangeListener is deprecated now.
Here is current way how to do it in fragment - change getActivity() with this for Activity:
private boolean mLocationPermissionGranted;
// The geographical location where the device is currently located. That is, the last-known
// location retrieved by the Fused Location Provider.
private Location mLastKnownLocation;
private long UPDATE_INTERVAL = 10 * 1000; /* 10 secs */
private long FASTEST_INTERVAL = 2000; /* 2 sec */
private FusedLocationProviderClient mFusedLocationProviderClient;
private void addLocationChangeListener(){
// Construct a FusedLocationProviderClient.
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getActivity());
// Create the location request to start receiving updates
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
//mLocationRequest.setMaxWaitTime(0);
//mLocationRequest.setSmallestDisplacement(0);
// Create LocationSettingsRequest object using location request
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest);
LocationSettingsRequest locationSettingsRequest = builder.build();
// Check whether location settings are satisfied
// https://developers.google.com/android/reference/com/google/android/gms/location/SettingsClient
SettingsClient settingsClient = LocationServices.getSettingsClient(getActivity());
settingsClient.checkLocationSettings(locationSettingsRequest);
// new Google API SDK v11 uses getFusedLocationProviderClient(this)
if (mLocationPermissionGranted) {
mFusedLocationProviderClient.requestLocationUpdates(mLocationRequest,
new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
// do work here
Location location = locationResult.getLastLocation();
}
},
Looper.myLooper());
} else {
getLocationPermission();
}
}

Google Maps Android API v2 don't show marker title

I tried some code to make Geocoding reverse location (using Google Maps Android API v2) and show title with marker, but the marker title didn't showed when I run my application.
Here is my code :
public class MainActivity extends FragmentActivity {
GoogleMap googleMap;
MarkerOptions markerOptions;
LatLng latLng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SupportMapFragment supportMapFragment = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map);
// Getting a reference to the map
googleMap = supportMapFragment.getMap();
// Setting a click event handler for the map
googleMap.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng arg0) {
// Getting the Latitude and Longitude of the touched location
latLng = arg0;
// Clears the previously touched position
googleMap.clear();
// Animating to the touched position
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
// Creating a marker
markerOptions = new MarkerOptions();
// Setting the position for the marker
markerOptions.position(latLng);
// Placing a marker on the touched position
googleMap.addMarker(markerOptions);
// Adding Marker on the touched location with address
new ReverseGeocodingTask(getBaseContext()).execute(latLng);
}
});
}
private class ReverseGeocodingTask extends AsyncTask<LatLng, Void, String>{
Context mContext;
public ReverseGeocodingTask(Context context){
super();
mContext = context;
}
// Finding address using reverse geocoding
#Override
protected String doInBackground(LatLng... params) {
Geocoder geocoder = new Geocoder(mContext);
double latitude = params[0].latitude;
double longitude = params[0].longitude;
List<Address> addresses = null;
String addressText="";
try {
addresses = geocoder.getFromLocation(latitude, longitude,1);
} catch (IOException e) {
e.printStackTrace();
}
if(addresses != null && addresses.size() > 0 ){
Address address = addresses.get(0);
addressText = String.format("%s, %s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getLocality(),
address.getCountryName());
}
return addressText;
}
#Override
protected void onPostExecute(String addressText) {
// Setting the title for the marker.
// This will be displayed on taping the marker
markerOptions.title(addressText);
// Placing a marker on the touched position
googleMap.addMarker(markerOptions);
}
}
}
Is there a problem with my code ?
change your code in onPostExecute()
googleMap
.addMarker(
new MarkerOptions()
.position(loc)
.draggable(true)
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.title(addressText))
.showInfoWindow();
Try this
public class MainActivity extends FragmentActivity {
GoogleMap googleMap;
MarkerOptions markerOptions;
LatLng latLng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SupportMapFragment supportMapFragment = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map);
// Getting a reference to the map
googleMap = supportMapFragment.getMap();
// Setting a click event handler for the map
googleMap.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng arg0) {
// Getting the Latitude and Longitude of the touched location
latLng = arg0;
// Clears the previously touched position
googleMap.clear();
// Animating to the touched position
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
// Creating a marker
markerOptions = new MarkerOptions();
// Setting the position for the marker
markerOptions.position(latLng);
// Placing a marker on the touched position
googleMap.addMarker(markerOptions);
// Adding Marker on the touched location with address
new GetAddressTask().execute(latLng);
// new ReverseGeocodingTask(MainActivity.this).execute(latLng);
}
});
}
public class GetAddressTask extends AsyncTask<LatLng, Void, Integer>{
private LatLng loc;
String addressText;
#Override
protected Integer doInBackground(LatLng... params) {
int mFinalFlag=0;
loc=params[0];
String filterAddress = "";
Geocoder geoCoder = new Geocoder(MainActivity.this, Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(loc.latitude,
loc.longitude, 1);
if (addresses!=null&&addresses.size() > 0) {
Address address = addresses.get(0);
addressText = String.format(
"%s, %s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getLocality(),
address.getCountryName());
}
} catch (IOException ex) {
} catch (Exception e2) {
e2.printStackTrace();
}
return mFinalFlag;
}
}
#Override
protected void onPostExecute(Integer result) {
googleMap.addMarker(
new MarkerOptions()
.position(loc)
.draggable(true)
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.title(addressText))
.showInfoWindow();
super.onPostExecute(result);
}
}

Get phone number from google map marker

I working with google map on android device , i am fetch information from markes , i am able to get marker title and maker snippet, but unable to get phone number information, please help me, thanks in advance.
package com.avion.mapdemo;
public class MainActivity extends Activity implements OnInfoWindowClickListener {
// Google Map
private GoogleMap googleMap;
MarkerOptions markerOptions;
LatLng latLng;
GPSTracker gps;
Address adrs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
// Loading map
initilizeMap();
// my location...
googleMap.setMyLocationEnabled(true);
// room setting from 2(min) to 21 (max)..
googleMap.animateCamera(CameraUpdateFactory.zoomTo(10.0f));
// get my location address......
myLocation();
} catch (Exception e) {
e.printStackTrace();
}
// marker information tab clicked...........
googleMap.setOnInfoWindowClickListener(this);
}
// method my location
private void myLocation() {
// TODO Auto-generated method stub
// for logitude and latitude..........
gps = new GPSTracker(MainActivity.this);
// check if GPS enabled
if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
//double latitude = 40.71958;
// double longitude = -74.09595;
// Toast.makeText(getApplicationContext(),latitude
// +"--"+longitude,Toast.LENGTH_SHORT).show();
// for address..........
Geocoder geocoder;
List<Address> addresses = null;
geocoder = new Geocoder(this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getAddressLine(1);
String country = addresses.get(0).getAddressLine(2);
Toast.makeText(getApplicationContext(),
address + "" + city + "" + country, Toast.LENGTH_LONG)
.show();
Log.e("strite", address);
Log.e("city", city);
Log.e("country", country);
// search string.....
// String addr="Hotel "+address
// +" "+city+" "+country;
String addr = "Bar" + " " + city + " " + country;
// call async task for load bars.....
new GeocoderTask().execute(addr);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/**
* function to load map. If map is not created it will create it for you
* */
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
// An AsyncTask class for accessing the GeoCoding Web Service
private class GeocoderTask extends AsyncTask<String, Void, List<Address>> {
#Override
protected List<Address> doInBackground(String... locationName) {
// Creating an instance of Geocoder class
// Geocoder transforming a street address or other description of a
// location
// into a (latitude, longitude) coordinate.
Geocoder geocoder = new Geocoder(getBaseContext());
List<Address> addresses = null;
try {
// Getting a maximum of 10 Address that matches the input text
addresses = geocoder.getFromLocationName(locationName[0], 10);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
#Override
protected void onPostExecute(List<Address> addresses) {
if (addresses == null || addresses.size() == 0) {
Toast.makeText(getBaseContext(), "No Bar found",
Toast.LENGTH_SHORT).show();
}
// Clears all the existing markers on the map
googleMap.clear();
// Adding Markers on Google Map for each matching address
for (int i = 0; i < addresses.size(); i++) {
// address Strings describing a location
adrs = (Address) addresses.get(i);
// Creating an instance of GeoPoint, to display in Google Map
// latLng class representing a pair of latitude and longitude
// coordinates,
latLng = new LatLng(adrs.getLatitude(), adrs.getLongitude());
// latLng = new LatLng(40.71958,-74.09595);
String addressText = String.format("%s, %s", adrs
.getMaxAddressLineIndex() > 0 ? adrs.getAddressLine(0)
: "", adrs.getCountryName());
// markerOptions to add property to marker
markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(adrs.getAddressLine(0));
markerOptions.snippet(adrs.getAddressLine(1) + ", "
+ adrs.getAddressLine(2) + ", "
+ adrs.getPhone());
/*
* getAddressLine(0) location name .
* getAddressLine(1) local address .
* getAddressLine(2) city,state .
* getAddressLine(3) country .
*/
googleMap.addMarker(markerOptions);
// Locate the first location
if (i == 0)
googleMap.animateCamera(CameraUpdateFactory
.newLatLng(latLng));
}
// end of loop.....
}
}
// on marker info tab click..
#Override
public void onInfoWindowClick(Marker marker) {
Toast.makeText(this, marker.getTitle() + "--" + marker.getSnippet(),
Toast.LENGTH_LONG).show();
}
}
You should split your Snippet Marker text and extract all the details.
see below
public void onInfoWindowClick(Marker marker) {
String[] str2 = marker.getSnippet().split(",");
String Addressline1=str2[0]; //Addressline 1
String Addressline2=str2[1]; //Addressline 2
String phone=str2[2]; //Phone
Toast.makeText(this, marker.getTitle() + "--" + marker.getSnippet()+"-- "+phone,
Toast.LENGTH_LONG).show();
}

Google map V2 giving the address of previous touched location

I am using Google map v2 in my app. i am placing the marker where i click. when i click again on map the privios marke gone and new marker added. when i check the address then it shows me the address of removed marker. i.e it contains the the last touched location.
Please help me. How can i remove address as well as marker removed. Here is my code
public class Map extends FragmentActivity {
GoogleMap gMap;
static int loginCheck = 0;
GeoPoint p, currentLocationPixels;
ConnectionDetector conDec;
ArrayList<HashMap<String, String>> aList = new ArrayList<HashMap<String, String>>();
SharedPreferences prefs;
LatLng latLng;
MarkerOptions markerOptions;
EditText desc;
String addressText = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
prefs = getApplicationContext().getSharedPreferences("jam",
MODE_PRIVATE);
conDec = new ConnectionDetector(this);
SupportMapFragment smf = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.mapView);
gMap = smf.getMap();
gMap.setMyLocationEnabled(true);
gMap.getUiSettings().setCompassEnabled(true);
// gMap.setTrafficEnabled(true);
gMap.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng arg0) {
// Getting the Latitude and Longitude of the touched location
latLng = arg0;
// Clears the previously touched position
gMap.clear();
addressText=null;
// Animating to the touched position
// gMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
int caller = getIntent().getIntExtra("button", 0);
System.out.println(caller);
switch (caller) {
case R.id.btMap:
gMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
gMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_annotation_darkblue)).title(addressText));
break;
case R.id.imageButton1:
gMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
gMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_annotation_bue)).title(addressText));
break;
case R.id.imageButton2:
gMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
gMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_annotation_green)).title(addressText));
break;
case R.id.imageButton3:
gMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
gMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_annotation_light)).title(addressText));
break;
case R.id.imageButton4:
gMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
gMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_annotation_purple)).title(addressText));
break;
case R.id.imageButton5:
gMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
gMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_annotation_red)).title(addressText));
break;
case R.id.imageButton6:
gMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
gMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_annotation_yellow)).title(addressText));
break;
}
// Creating a marker
// markerOptions = new MarkerOptions();
// Setting the position for the marker
// markerOptions.position(latLng);
// Placing a marker on the touched position
// gMap.addMarker(markerOptions);
// Adding Marker on the touched location with address
new ReverseGeocodingTask(getBaseContext()).execute(latLng);
}
});
// ** Hide By Gaurav
// gMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
// #Override
// public void onInfoWindowClick(Marker marker) {
// System.out.println(marker.getPosition().latitude);
//
// Intent i = new Intent(Map.this, Detail.class);
// i.putExtra("lat", "" + marker.getPosition().latitude);
// i.putExtra("lng", "" + marker.getPosition().longitude);
// i.putExtra("title", marker.getTitle());
// i.putExtra("desc", marker.getSnippet());
// startActivity(i);
// }
// });
getInfo();
CameraPosition cp = new CameraPosition.Builder()
.target(new LatLng(Double.parseDouble("30.7353"), Double
.parseDouble("76.7911"))).zoom(16).build();
gMap.animateCamera(CameraUpdateFactory.newCameraPosition(cp));
}
// ** Gaurav Work Start Here
private class ReverseGeocodingTask extends AsyncTask<LatLng, Void, String> {
Context mContext;
public ReverseGeocodingTask(Context context) {
super();
mContext = context;
}
// Finding address using reverse geocoding
#Override
protected String doInBackground(LatLng... params) {
Geocoder geocoder = new Geocoder(mContext);
double latitude = params[0].latitude;
double longitude = params[0].longitude;
List<Address> addresses = null;
//String addressText = "";
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
addressText = String.format(
"%s, %s, %s",
address.getMaxAddressLineIndex() > 0 ? address
.getAddressLine(0) : "", address.getLocality(),
address.getCountryName());
}
return addressText;
}
// #Override
// protected void onPostExecute(String addressText) {
//
// // This will be displayed on taping the marker
// markerOptions.title(addressText);
//
// // Placing a marker on the touched position
// gMap.addMarker(markerOptions);
//
// }
}}
I have solved this with. its my own mistake. it will help you.
public class Map extends FragmentActivity {
GoogleMap gMap;
static int loginCheck = 0;
GeoPoint p, currentLocationPixels;
ConnectionDetector conDec;
ArrayList<HashMap<String, String>> aList = new ArrayList<HashMap<String, String>>();
SharedPreferences prefs;
LatLng latLng;
MarkerOptions markerOptions;
EditText desc;
String selectedLocAddress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
prefs = getApplicationContext().getSharedPreferences("jam",
MODE_PRIVATE);
conDec = new ConnectionDetector(this);
SupportMapFragment smf = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.mapView);
gMap = smf.getMap();
gMap.setMyLocationEnabled(true);
gMap.getUiSettings().setCompassEnabled(true);
// gMap.setTrafficEnabled(true);
// ** Gaurav Works Start Here
gMap.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng arg0) {
// Getting the Latitude and Longitude of the touched location
latLng = arg0;
// Clears the previously touched position
gMap.clear();
// Animating to the touched position
gMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
// Adding Marker on the touched location with address
new ReverseGeocodingTask(getBaseContext()).execute(latLng);
}
});
// ** Hide By Gaurav
gMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
public void onInfoWindowClick(Marker marker) {
System.out.println(marker.getPosition().latitude);
Intent i = new Intent(Map.this, Detail.class);
startActivity(i);
}
});
getInfo();
CameraPosition cp = new CameraPosition.Builder()
.target(new LatLng(Double.parseDouble("30.7353"), Double
.parseDouble("76.7911"))).zoom(16).build();
gMap.animateCamera(CameraUpdateFactory.newCameraPosition(cp));
}
// ** Gaurav Work Start Here
private class ReverseGeocodingTask extends AsyncTask<LatLng, Void, String> {
Context mContext;
public ReverseGeocodingTask(Context context) {
super();
mContext = context;
}
// Finding address using reverse geocoding
#Override
protected String doInBackground(LatLng... params) {
Geocoder geocoder = new Geocoder(mContext);
double latitude = params[0].latitude;
double longitude = params[0].longitude;
List<Address> addresses = null;
String addressText = "";
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
addressText = String.format("%s, %s, %s",address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getLocality(),address.getCountryName());
}
} catch (IOException e) {
e.printStackTrace();
}
return addressText;
}
// #Override
protected void onPostExecute(String addressText) {
selectedLocAddress = addressText;
int caller = getIntent().getIntExtra("button", 0);
System.out.println(caller);
switch (caller) {
case R.id.btMap:
gMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_annotation_darkblue)).title(selectedLocAddress));
System.out.println("selectedLocAddress");
break;
case R.id.imageButton1:
gMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_annotation_bue)).title(selectedLocAddress));
break;
case R.id.imageButton2:
gMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_annotation_green)).title(selectedLocAddress));
break;
case R.id.imageButton3:
gMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_annotation_light)).title(selectedLocAddress));
break;
case R.id.imageButton4:
gMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_annotation_purple)).title(selectedLocAddress));
break;
case R.id.imageButton5:
gMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_annotation_red)).title(selectedLocAddress));
break;
case R.id.imageButton6:
gMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_annotation_yellow)).title(selectedLocAddress));
break;
}
//
// // This will be displayed on taping the marker
// markerOptions.title(addressText);
//
// // Placing a marker on the touched position
// gMap.addMarker(markerOptions);
//
}
}

java.util.arraylist cannot be cast to android.location.address

Im trying to put all addresses (Strings) into a list and then get them one by one and populate a map with markers, but i get this error saing that java.util.arraylist cannot be cast to android.location.address. any help?
this is the snipet of code that generates the error
int i = 0;
List<List<Address>> addressList = new ArrayList<List<Address>>();
//while (indirizzi != null) {
while (i <= 3) {
try {
addressList.add(geocoder.getFromLocationName(indirizzi.get(i), 1));
Log.i("indirizzo i-esimo",indirizzi.get(i));
i++;
} catch (IOException e) {
Log.i("geolocation","geolocation IOException");
e.printStackTrace();
}
}
for (int j = 0; j < addressList.size(); j++) {
Address address = (Address) addressList.get(j);
if(address.hasLatitude() && address.hasLongitude()){
latLng = new LatLng(address.getLatitude(), address.getLongitude());
}
markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(indirizzi.get(i));
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.icn_albero));
Log.i("for", Integer.toString(i));
j++;
googleMap.addMarker(markerOptions);
}
Look at the definition , it is a List of List of Address.
List<List<Address>> addressList = new ArrayList<List<Address>>();
You cannot do this :
Address address = (Address) addressList.get(j);
As this will give you a List<Address> which is not an Address object.
You can possibly do :
Address address = (Address) addressList.get(j).get(someOtherIndex);
Define the List as :
List<Address> addressList = new ArrayList<Address>();
I have Used the below code.
I have called the GeocoderTask class from the oncreate.
ed.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
addresstext = (String) parent.getItemAtPosition(position);
Toast.makeText(getBaseContext(),""+addresstext+ "", Toast.LENGTH_SHORT).show();
if(addresstext!=null && !addresstext.equals("")){
new GeocoderTask().execute(addresstext);
}
}
});
-
private class GeocoderTask extends AsyncTask<String, Void, List<Address>>{
#Override
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 10 Address that matches the input text
addresses = geocoder.getFromLocationName(locationName[0], 10);
System.out.println(" Inside Background Process");
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
#Override
protected void onPostExecute(List<Address> addresses) {
if(addresses==null || addresses.size()==0){
Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
}
// Clears all the existing markers on the map
if(marker!=null){
marker.remove();
}
// 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
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
addressText = String.format("%s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getCountryName());
System.out.println(" Inside OnPostExecutemeathod Process");
Toast.makeText(getBaseContext(), ""+address.getLatitude()+" - "+address.getLongitude()+"", Toast.LENGTH_SHORT).show();
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng) // Sets the center of the map to Mountain View
.zoom(17) // Sets the zoom
.bearing(90) // Sets the orientation of the camera to east
.tilt(30) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 18));
marker = map.addMarker(new MarkerOptions()
.position(latLng)
.title(""+addresstext+""));
marker.showInfoWindow();
}
}

Categories

Resources