Get phone number from google map marker - android

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

Related

I do not receive the address of my location (java.lang.IndexOutOfBoundsException: Index: 0 Size: 0)

I have a code that has to return the coordinates and the address of the coordinates of my device and the place I select on the map, the application gives me the coordinates rounded of my device, but it does not return the address, instead what is returned to me is an error:
java.lang.IndexOutOfBoundsException: Index: 0 Size: 0
But when selecting a place on the map, it returns the complete coordinates and also its address.
This is the code:
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.camera_fragment, container, false);
myplacebtn = (Button) view.findViewById(R.id.myplacebtn);//Button --get my location
myplacebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (validatePermissionsLocation()) {
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(getActivity(),
android.Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
return;
}
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationListener()
);
showCurrentLocation();
}
}
});
//create the map
mapView = (MapView) view.findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
//get a MapView
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
//Crea marker when i select a place in the map
// Setting a click event handler for the map
map.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
//Make the Address
getAddress(latLng);
}
});
map.getUiSettings().setMyLocationButtonEnabled(false);
LatLng jerusalem = new LatLng(32.1105435, 34.8683683);
CameraUpdate miLocation = CameraUpdateFactory.newLatLngZoom(jerusalem, 11);
map.moveCamera(CameraUpdateFactory.newLatLng(jerusalem));
googleMap.animateCamera(miLocation);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(jerusalem);
if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(),
android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
}
});
return view;
}
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
}
public void onStatusChanged(String s, int i, Bundle b) {
}
public void onProviderDisabled(String s) {
// gpsDialog();
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
public void onProviderEnabled(String s) {
}
}
//Location of my device
protected void showCurrentLocation() {
if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(),
android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
//setCoordinates.setText(location.getLatitude() + " , " +
location.getLongitude());
LatLng latLng=new
LatLng(location.getLatitude(),location.getLongitude());
//Make Address
getAddress(latLng);
CameraUpdate miLocation = CameraUpdateFactory.newLatLngZoom(latLng,11);
map.animateCamera(miLocation);
}
}
//Method return the coordinates and the address
private void getAddress(LatLng latLng){
Geocoder geocoder;
List<android.location.Address> direccion = null;
geocoder = new Geocoder(getActivity(), Locale.getDefault());
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
try {
direccion = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1); // 1 representa la cantidad de resultados a obtener
String address = direccion.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String city = direccion.get(0).getLocality();
// Setting the title for the marker.
// This will be displayed on taping the marker
markerOptions.title(city + " : " + address);
} catch (IOException e) {
Toast.makeText(getActivity(),e.toString(),Toast.LENGTH_LONG).show();
markerOptions.title(latLng.latitude + " , " + latLng.longitude);
}
catch (Exception e){
Toast.makeText(getActivity(),e.toString(),Toast.LENGTH_LONG).show();
markerOptions.title(latLng.latitude + " , " + latLng.longitude);
}
// Setting the position for the marker
markerOptions.position(latLng);
setCoordinates.setText(latLng.latitude + " , " + latLng.longitude);
latitude = latLng.latitude;
longitude = latLng.longitude;
// Clears the previously touched position
map.clear();
// Animating to the touched position
map.animateCamera(CameraUpdateFactory.newLatLng(latLng));
// Placing a marker on the touched position
map.addMarker(markerOptions);
}
Before access data from list first Check it empty or null
if (direccion!= null && !direccion.isEmpty()){
String address = direccion.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String city = direccion.get(0).getLocality();
// Setting the title for the marker.
// This will be displayed on taping the marker
markerOptions.title(city + " : " + address);
}
Clearly, your issue is with this method :
//Method return the coordinates and the address
private void getAddress(LatLng latLng){
Geocoder geocoder;
List<android.location.Address> direccion = null;
geocoder = new Geocoder(getActivity(), Locale.getDefault());
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
try {
direccion = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1); // 1 representa la cantidad de resultados a obtener
String address = direccion.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String city = direccion.get(0).getLocality();
// Setting the title for the marker.
// This will be displayed on taping the marker
markerOptions.title(city + " : " + address);
} catch (IOException e) {
Toast.makeText(getActivity(),e.toString(),Toast.LENGTH_LONG).show();
markerOptions.title(latLng.latitude + " , " + latLng.longitude);
}
catch (Exception e){
Toast.makeText(getActivity(),e.toString(),Toast.LENGTH_LONG).show();
markerOptions.title(latLng.latitude + " , " + latLng.longitude);
}
// Setting the position for the marker
markerOptions.position(latLng);
setCoordinates.setText(latLng.latitude + " , " + latLng.longitude);
latitude = latLng.latitude;
longitude = latLng.longitude;
// Clears the previously touched position
map.clear();
// Animating to the touched position
map.animateCamera(CameraUpdateFactory.newLatLng(latLng));
// Placing a marker on the touched position
map.addMarker(markerOptions);
}
here, this block
try {
direccion = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1); // 1 representa la cantidad de resultados a obtener
String address = direccion.get(0).getAddressLine(0); // crash happens here
String city = direccion.get(0).getLocality();
// Setting the title for the marker.
// This will be displayed on taping the marker
markerOptions.title(city + " : " + address);
}
is getting crash because for some devices, old approach (above one) to reverse geocoding is not working anymore (for atleast some of devices it returns empty).
So , you'd have to convert address from Geocoding API.
you can check how to from here : Reference for reverse geocode

how to convert longitude and latitude into text format to show street address?

I am developing an app,In this I'm using google map to show users current location.
Following code I am using but it doesn't give the result of street address only shows the current location in map and shows longitude and latitude.How do I show the current street address in text field from current longitude and latitude?
//java
public class LocationActivity extends Activity {
private TextView locationText;
private TextView addressText, textview;
private GoogleMap map;
String mob_no;
private boolean loggedIn = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
locationText = (TextView) findViewById(R.id.location);
addressText = (TextView) findViewById(R.id.address);
// textview=(TextView)findViewById(R.id.textView_euser);
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF, false);
mob_no = sharedPreferences.getString(Config.PHONE_SHARED_PREF, "Not Available");
// textview.setText(String.valueOf(mob_no));
//replace GOOGLE MAP fragment in this Activity
replaceMapFragment();
}
private void replaceMapFragment() {
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
// Enable Zoom
map.getUiSettings().setZoomGesturesEnabled(true);
//set Map TYPE
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//enable Current location Button
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
map.setMyLocationEnabled(true);
//set "listener" for changing my location
map.setOnMyLocationChangeListener(myLocationChangeListener());
}
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener() {
return new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
double longitude = location.getLongitude();
double latitude = location.getLatitude();
Marker marker;
marker = map.addMarker(new MarkerOptions().position(loc));
map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
locationText.setText("You are at [" + longitude + " ; " + latitude + " ]");
//get current address by invoke an AsyncTask object
new GetAddressTask(LocationActivity.this).execute(String.valueOf(latitude), String.valueOf(longitude));
// getCompleteAddressString(longitude,latitude);
}
};
}
public void callBackDataFromAsyncTask(String address) {
addressText.setText(address);
}
/* #SuppressLint("LongLogTag")
private String getCompleteAddressString(double LATITUDE, double LONGITUDE) {
String strAdd = "";
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if (addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:");
for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
strAdd = strReturnedAddress.toString();
addressText.setText(strAdd);
Log.w("My Current loction address", "" + strReturnedAddress.toString());
} else {
Log.w("My Current loction address", "No Address returned!");
}
} catch (Exception e) {
e.printStackTrace();
Log.w("My Current loction address", "Canont get Address!");
}
return strAdd;
} */
}
//getaddress
public class GetAddressTask extends AsyncTask<String, Void, String> {
private LocationActivity activity;
public GetAddressTask(LocationActivity activity) {
super();
this.activity = activity;
}
#Override
protected String doInBackground(String... params) {
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(activity, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(Double.parseDouble(params[0]), Double.parseDouble(params[1]), 1);
//get current Street name
String address = addresses.get(0).getAddressLine(0);
//get current province/City
String province = addresses.get(0).getAdminArea();
//get country
String country = addresses.get(0).getCountryName();
//get postal code
String postalCode = addresses.get(0).getPostalCode();
//get place Name
String knownName = addresses.get(0).getFeatureName(); // Only if available else return NULL
return "Street: " + address + "\n" + "City/Province: " + province + "\nCountry: " + country
+ "\nPostal CODE: " + postalCode + "\n" + "Place Name: " + knownName;
} catch (IOException ex) {
ex.printStackTrace();
return "IOE EXCEPTION";
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
return "IllegalArgument Exception";
}
}
/**
* When the task finishes, onPostExecute() call back data to Activity UI and displays the address.
* #param address
*/
#Override
protected void onPostExecute(String address) {
// Call back Data and Display the current address in the UI
activity.callBackDataFromAsyncTask(address);
}
}
You can use Double.toString() to convert a double to a String. Alternatively, you can use +:
"" + latitude
If you need more control over the output, such as the number of decimal places to display, you can use String.format().
public static void getAddressFromLocation(final double latitude, final double longitude,
final Context context, final Handler handler) {
Thread thread = new Thread() {
#Override
public void run() {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
try {
List<Address> addressList = geocoder.getFromLocation(
latitude, longitude, 1);
if (addressList != null && addressList.size() > 0) {
Address address = addressList.get(0);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
sb.append(address.getAddressLine(i)).append("\n");
}
sb.append(address.getLocality()).append("\n");
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
result = sb.toString();
}
} catch (IOException e) {
Log.e(TAG, "Unable connect to Geocoder", e);
} finally {
Message message = Message.obtain();
message.setTarget(handler);
if (result != null) {
message.what = 1;
Bundle bundle = new Bundle();
result = "Latitude: " + latitude + " Longitude: " + longitude +
"\n\nAddress:\n" + result;
bundle.putString("address", result);
message.setData(bundle);
} else {
message.what = 1;
Bundle bundle = new Bundle();
result = "Latitude: " + latitude + " Longitude: " + longitude +
"\n Unable to get address for this lat-long.";
bundle.putString("address", result);
message.setData(bundle);
}
message.sendToTarget();
}
}
};
thread.start();
}
more info please check below link:-
http://javapapers.com/android/android-get-address-with-street-name-city-for-location-with-geocoding/
its helps to you

Getting different latitude and longitude value for same location by searching through EditText and by clicking on the map

public class AddNewLocationActivity extends Activity {
GoogleMap googleMap;
EditText edtLocation;
Marker marker;
List<Address> addressList = null;
VibRIngDatabase vibRIngDatabase;
double latitude, longitude;
Geocoder geocoder;
LatLng latLng;
String locationAddress, name, mode;
AlertDialog.Builder dialogBuilder;
double lati1, longi1;
TextView lat, longi, location_name;
RadioButton selectedModeRadioButton;
RadioGroup rg;
Button setMode;
int selectedId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addnewlocation);
createMapView();// Rendering the Google Map in the fragment
addMarkerAtCurrent(); // Adding marker at the current location of the device
mapClick(); // On clicking the map
vibRIngDatabase = new VibRIngDatabase(this);
}
//Display the Google Map inside the fragment
private void createMapView() {
try {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
googleMap.setMyLocationEnabled(true); //To See my current location
/**
* If the map is still null after attempted initialisation,
* show an error to the user
*/
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Error creating map", Toast.LENGTH_SHORT).show();
}
}
} catch (NullPointerException exception) {
Log.e("mapApp", exception.toString());
}
}
// Adding marker to the current location
public void addMarkerAtCurrent() {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Get Current Location
Location myLocation = locationManager.getLastKnownLocation(provider);
// set map type
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// Get latitude of the current location
latitude = myLocation.getLatitude();
// Get longitude of the current location
longitude = myLocation.getLongitude();
// Create a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
String address = getLocationAddress(latitude, longitude);
marker = googleMap.addMarker(
new MarkerOptions()
.position(new LatLng(latitude, longitude))
.title(address));
// Show the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(14));
}
public LatLng search(View v) {
edtLocation = (EditText) findViewById(R.id.edtLocation);
String location = edtLocation.getText().toString();
if (location != null) {
Geocoder geocoder = new Geocoder(this);
try {
addressList = geocoder.getFromLocationName(location, 1);
} catch (IOException e) {
e.printStackTrace();
}
// To get address from list<Address>
Address address = addressList.get(0);
String locality = address.getLocality();
String adminArea = address.getAdminArea();
String locationAddress = locality + " " + adminArea;
latitude = address.getLatitude();
longitude = address.getLongitude();
latLng = new LatLng(latitude, longitude);
googleMap.clear();
marker = googleMap.addMarker(new MarkerOptions().position(latLng).title(locationAddress));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(14));
}
return latLng;
}
// Clicking the GoogleMap
public LatLng mapClick() {
googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng arg) {
latLng = arg;
latitude = latLng.latitude;
longitude = latLng.longitude;
String name = getLocationAddress(latitude, longitude);
googleMap.clear();
marker = googleMap.addMarker(new MarkerOptions().position(latLng).title(locationAddress));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
});
return latLng;
}
public String getLocationAddress(double lat, double longi) {
latitude = lat;
longitude = longi;
geocoder = new Geocoder(getApplicationContext());
try {
addressList = geocoder.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
Address address = addressList.get(0);
String addressLine = address.getAddressLine(0);
String locality = address.getLocality();
String adminArea = address.getAdminArea();
locationAddress = addressLine + " " + locality + " " + adminArea;
return locationAddress;
}
// On clicking add button openDialog method will be called
public void openDialog(View v) {
dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.custom_dialog, null, false);
dialogBuilder.setTitle("Set Mode");
dialogBuilder.setView(view);
AlertDialog dialog = dialogBuilder.create();
dialog.show();
lat = (TextView) view.findViewById(R.id.lblLatitude);
longi = (TextView) view.findViewById(R.id.lblLongitude);
location_name = (TextView) view.findViewById(R.id.lblLocationName);
setMode = (Button) view.findViewById(R.id.btnSetMode);
latLng = marker.getPosition();
lati1 = latLng.latitude;
longi1 = latLng.longitude;
name = getLocationAddress(lati1, longi1);
lat.setText(Double.toString(lati1));
longi.setText(Double.toString(longi1));
location_name.setText(name);
rg = (RadioGroup) view.findViewById(R.id.modesRadioGroup);
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.vibrationRadioButton:
Toast.makeText(getApplicationContext(), "Vibration clicked", Toast.LENGTH_LONG).show();
break;
case R.id.muteRadioButton:
Toast.makeText(getApplicationContext(), "Mute clicked", Toast.LENGTH_LONG).show();
break;
case R.id.ringingRadioButton:
Toast.makeText(getApplicationContext(), "Ringing clicked", Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
});
}
}
Here in this code ,I am using the concept of Google Map.We can search a location by entering location name through EditText and then clicking on Search Button which call search() method .Here i will get the latitude and logitude of entered location.Also i can click on map which will call onMapClick() method.Here also i can get the latitude and longitude of the clicked position.While executing this code , i am getting different latitude and longitude value using these 2 methods for the same location.Just focus on search() and onMapClick() method .Please help me the resolve the issue.

How to get address from latitude and longitude android google map v2 [duplicate]

This question already has answers here:
get latitude and longitude with geocoder and android Google Maps API v2
(5 answers)
Closed 7 years ago.
I am trying to get an address from latitude and longitude in Android Google Maps v2, but it errors.
Here is my code:
case PLACES_DETAILS :
final HashMap<String, String> hm = result.get(0);
final double latitude = Double.parseDouble(hm.get("lat"));
final double longitude = Double.parseDouble(hm.get("lng"));
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
googleMap = fm.getMap();
final LatLng point = new LatLng(latitude, longitude);
CameraUpdate cameraPosition = CameraUpdateFactory.newLatLngZoom(point, 10);
CameraUpdate cameraZoom = CameraUpdateFactory.zoomBy(5);
googleMap.moveCamera(cameraPosition);
googleMap.animateCamera(cameraZoom);
googleMap.getCameraPosition();
//Log.e("Lat", String.valueOf(googleMap.getCameraPosition().target.latitude));
//Log.e("Long", String.valueOf(googleMap.getCameraPosition().target.latitude));
//googleMap.setOnMyLocationChangeListener(myLocationChangeListener);
googleMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition cameraPosition) {
Log.e("Lat", String.valueOf(googleMap.getCameraPosition().target.latitude));
Log.e("Long", String.valueOf(googleMap.getCameraPosition().target.longitude));
}
});
Use the following code snippet:
try {
Geocoder geo = new Geocoder(youractivityclassname.this.getApplicationContext(), Locale.getDefault());
List<Address> addresses = geo.getFromLocation(latitude, longitude, 1);
if (addresses.isEmpty()) {
yourtextfieldname.setText("Waiting for Location");
}
else {
if (addresses.size() > 0) {
yourtextfieldname.setText(addresses.get(0).getFeatureName() + ", " + addresses.get(0).getLocality() +", " + addresses.get(0).getAdminArea() + ", " + addresses.get(0).getCountryName());
//Toast.makeText(getApplicationContext(), "Address:- " + addresses.get(0).getFeatureName() + addresses.get(0).getAdminArea() + addresses.get(0).getLocality(), Toast.LENGTH_LONG).show();
}
}
}
catch (Exception e) {
e.printStackTrace(); // getFromLocation() may sometimes fail
}
reference :
https://mobiforge.com/design-development/using-google-maps-android
This should give you the address for your lat long
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(mContext, Locale.getDefault());
try {
String sPlace;
addresses = geocoder.getFromLocation(mLat, mLong, 1);
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getAddressLine(1);
String country = addresses.get(0).getAddressLine(2);
String[] splitAddress = address.split(",");
sPlace = splitAddress[0] + "\n";
if(city != null && !city.isEmpty()) {
String[] splitCity = city.split(",");
sPlace += splitCity[0];
}
} catch (IOException e) {
e.printStackTrace();
}
I am giving you my code, i use this code,2 months ago.. I didn't able to test this code right now, but it worked that time. may u need to modify some lines.
use this function
public void getAddressByLatLong(){
latitude = bundle.getDouble("Lat");
longitude = bundle.getDouble("Long");
LatLng pos = new LatLng(latitude, longitude);
try {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager()
.findFragmentById(R.id.map)).getMap();
}
googleMap.setMapType(googleMap.MAP_TYPE_HYBRID);
LocationManager location_manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener listner = new MyLocationListner();
location_manager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 3000, 5000, listner);
} catch (Exception e) {
e.printStackTrace();
}
}
Create a class
public class MyLocationListner implements LocationListener {
#SuppressLint("NewApi")
#SuppressWarnings("static-access")
#Override
public void onLocationChanged(Location arg0) {
Toast.makeText(getApplicationContext(),
"In on Location Changed", Toast.LENGTH_SHORT).show();
// TODO Auto-generated method stub
getLatitude = "" + arg0.getLatitude();
getLongitude = "" + arg0.getLongitude();
// lati.setText(getLatitude + "," + getLongitude);
latitude = arg0.getLatitude();
longitude = arg0.getLongitude();
try {
geocoder = new Geocoder(DisplayActivity.this, Locale.ENGLISH);
addresses = geocoder.getFromLocation(latitude, longitude, 1);
if (geocoder.isPresent()) {
Toast.makeText(getApplicationContext(), "geocoder present",
Toast.LENGTH_SHORT).show();
Address returnAddress = addresses.get(0);
String localityString = returnAddress.getLocality();
String city = returnAddress.getCountryName();
String region_code = returnAddress.getCountryCode();
String zipcode = returnAddress.getPostalCode();
str = new StringBuilder();
str.append(localityString + " ");
str.append(city + " ");
str.append(region_code + " ");
str.append(zipcode + " ");
// Add = str.toString();
// longi.setText(str);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(latitude, longitude)).zoom(2)
.build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
MarkerOptions marker = new MarkerOptions().position(
new LatLng(latitude, longitude)).title(
str.toString());
marker.icon(BitmapDescriptorFactory
.fromResource(R.drawable.mario));
googleMap.addMarker(marker);
Toast.makeText(getApplicationContext(), str,
Toast.LENGTH_SHORT).show();
} else
Toast.makeText(getApplicationContext(),
"geocoder not present", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Exception",
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onProviderDisabled(String arg0) {
}
#Override
public void onProviderEnabled(String arg0) {
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
}

How to reverse Geocode in google maps api 2 android

I want to do reverse geocoding in my app using map api 2.But i dont know exactly how to do that?Any ideas?
Use Geocoder:
Geocoder geoCoder = new Geocoder(context);
List<Address> matches = geoCoder.getFromLocation(latitude, longitude, 1);
Address bestMatch = (matches.isEmpty() ? null : matches.get(0));
This is how it works for me..
MarkerOptions markerOptions;
Location myLocation;
Button btLocInfo;
String selectedLocAddress;
private GoogleMap myMap;
LatLng latLng;
LatLng tmpLatLng;
#Override
public void onMapLongClick(LatLng point) {
// Getting the Latitude and Longitude of the touched location
latLng = point;
// Clears the previously touched position
myMap.clear();
// Animating to the touched position
myMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
// Creating a marker
markerOptions = new MarkerOptions();
// Setting the position for the marker
markerOptions.position(latLng);
// Adding Marker on the touched location with address
new ReverseGeocodingTask(getBaseContext()).execute(latLng);
//tmpLatLng = latLng;
btLocInfo.setEnabled(true);
btLocInfo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
double[] coordinates={tmpLatLng.latitude/1E6,tmpLatLng.longitude/1E6};
double latitude = tmpLatLng.latitude;
double longitude = tmpLatLng.longitude;
Log.i("selectedCoordinates", latitude + " " + longitude);
Log.i("selectedLocAddress", selectedLocAddress);
}
});
}
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);
Thread.sleep(500);
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();
} catch (InterruptedException e) {
e.printStackTrace();
}
selectedLocAddress = addressText;
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
myMap.addMarker(markerOptions);
}
}
You can do like this to get complete address :
public class MainActivity extends AppCompatActivity {
...
private Geocoder geocoder;
private TextView mAddressTxtVu;
...
// assume that you got latitude and longitude correctly
mLatitude = 20.23232
mLongitude = 32.999
String errorMessage = "";
geocoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(
mlattitude,
mlongitude,
1);
} catch (IOException e) {
errorMessage = getString(R.string.service_not_available);
Log.e(TAG, errorMessage, e);
} catch (IllegalArgumentException illegalArgumentException) {
// Catch invalid latitude or longitude values.
errorMessage = getString(R.string.invalid_lat_long_used);
Log.e(TAG, errorMessage + ". " + "Latitude = " + mlattitude +",
Longitude = " + mlongitude, illegalArgumentException);
}
// Handle case where no address was found.
if (addresses == null || addresses.size() == 0) {
if (errorMessage.isEmpty()) {
errorMessage = getString(R.string.no_address_found);
Log.e(TAG, errorMessage);
}
} else {
Address address = addresses.get(0);
ArrayList<String> addressFragments = new ArrayList<String>();
// Fetch the address lines using getAddressLine,
// join them, and send them to the thread.
for (int i = 0; i <= address.getMaxAddressLineIndex(); i++) {
addressFragments.add(address.getAddressLine(i));
}
// Log.i(TAG, getString(R.string.address_found));
mAddressTxtVu.setText(TextUtils.join(System.getProperty("line.separator"),
addressFragments));
}
Hope it helps!
You don't need to use Google Maps Api for this purpose. Android SKD have a class for it which you can simply use without any registration of API Key and so on. The class is android.location.Geocoder. It have methods for geocoding and reverse geocoding. I was looking in the source code of this class and found that it have a method android.location.Geocoder#getFromLocationName(java.lang.String, int) where first argument is address, and second is max number of results you want. It returns a List<Address>. The Address class have methods like android.location.Address#getLatitude and android.location.Address#getLongitude. They both return double.
Try it and let me know how good it is :-)

Categories

Resources