Google Maps Android API v2 don't show marker title - android

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

Related

Marker taps are not always recognized android

I have included Google Map in my app and added 4 markers in the map by using a for loop. I also managed to get the zip code, the name of the city and the adress of these added markers by using Geocoder.
It all works, but the problem is that clicks on the markers do not always seem to work. Sometimes I have to make double taps to see the title of the markers. I really don't know why. Here is my full code
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
String city, adress, zip;
Marker marker;
LatLngBounds.Builder builder = new LatLngBounds.Builder();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng[] point_new = new LatLng[4];
point_new[0] = new LatLng(52.4788535, 13.32730760000004);
point_new[1] = new LatLng(52.4794297, 13.313520799999992);
point_new[2] = new LatLng(52.5272885, 13.458033200000045);
point_new[3] = new LatLng(52.52603999999999, 13.488159999999993);
for (int i = 0; i < point_new.length; i++) {
drawMarker(point_new[i]);
marker = mMap.addMarker(new MarkerOptions().position(point_new[i]));
mMap.moveCamera(CameraUpdateFactory.newLatLng(point_new[i]));
}
getAdress(52.4788535, 13.32730760000004 );
marker = mMap.addMarker(new MarkerOptions().position(point_new[0]).title(adress+"," + zip + "" + city));
getAdress(52.4794297, 13.313520799999992);
marker = mMap.addMarker(new MarkerOptions().position(point_new[1]).title(adress+"," + zip + "" + city));
getAdress(52.5272885, 13.458033200000045);
marker = mMap.addMarker(new MarkerOptions().position(point_new[2]).title(adress+"," + zip + "" + city));
getAdress(52.52603999999999, 13.488159999999993);
marker = mMap.addMarker(new MarkerOptions().position(point_new[3]).title(adress+"," + zip + "" + city));
for (int j = 0; j < point_new.length; j++) {
builder.include(point_new[j]);
}
LatLngBounds bounds = builder.build();
mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 20));
}
public void drawMarker(LatLng point) {
// Creating an instance of MarkerOptions
MarkerOptions markerOptions = new MarkerOptions();
// Setting latitude and longitude for the marker
markerOptions.position(point);
// Adding marker on the Google Map
mMap.addMarker(markerOptions);
}
public void getAdress(double lat, double lng){
Geocoder geocoder = new Geocoder(MapsActivity.this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(lat,lng,1);
} catch (IOException e) {
e.printStackTrace();
}
city = addresses.get(0).getLocality();
adress = addresses.get(0).getAddressLine(0);
zip = addresses.get(0).getPostalCode();
}
}
try this code, i have tested, its working
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
List<MarkerDesc> markerDescList = new ArrayList<>();
markerDescList.add(new MarkerDesc(new LatLng(52.4788535, 13.32730760000004), getAdress(52.4788535, 13.32730760000004)));
markerDescList.add(new MarkerDesc(new LatLng(52.4794297, 13.313520799999992), getAdress(52.4794297, 13.313520799999992)));
markerDescList.add(new MarkerDesc(new LatLng(52.5272885, 13.458033200000045), getAdress(52.5272885, 13.458033200000045)));
markerDescList.add(new MarkerDesc(new LatLng(52.52603999999999, 13.488159999999993), getAdress(52.52603999999999, 13.488159999999993)));
for(int i=0; i<markerDescList.size(); i++){
MarkerDesc markerDesc = markerDescList.get(i);
mMap.addMarker(new MarkerOptions()
.position(markerDesc.getLatLng())
.title(markerDesc.getAddresses().get(0).getLocality())
.snippet(markerDesc.getAddresses().get(0).getAddressLine(0)+"\n"+markerDesc.getAddresses().get(0).getPostalCode()+"\n"+markerDesc.getAddresses().get(0).getLocality())
.icon(BitmapDescriptorFactory.defaultMarker()));
}
LatLng latLng = markerDescList.get(markerDescList.size()-1).getLatLng();
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition.Builder().target(latLng).zoom(15).bearing(0).tilt(25).build()));
}
public List<Address> getAdress(double lat, double lng){
Geocoder geocoder = new Geocoder(MapsActivity.this, Locale.getDefault());
try {
return geocoder.getFromLocation(lat,lng,1);
} catch (IOException e) {
e.printStackTrace();
}
/*String city = addresses.get(0).getLocality();
String adress = addresses.get(0).getAddressLine(0);
String zip = addresses.get(0).getPostalCode();*/
return null;
}
private class MarkerDesc{
LatLng latLng;
List<Address> addresses;
private MarkerDesc(LatLng ltLng, List<Address> addr){
this.latLng=ltLng;
this.addresses = addr;
}
private LatLng getLatLng() {
return latLng;
}
private List<Address> getAddresses() {
return addresses;
}
}
}

Add second marker on google maps activity in android on user input

I have a google maps activity with a map an edittext and a button.
The screenshot of the activity that I have ready at the moment.
Whenever this activity is opened a marker is added to the map.
What I want further in this is that whenever the user inputs an address in that edittext and clicks the button, then another marker is added on the same map without erasing the previous marker and a polyline is created in the map joining the two markers.
I have tried adding the second marker but the app just crashes and I am not able to do that. It would be a great help if you guys can help me in adding the second marker.
Here is the activity code :
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private EditText findRouteEdittext;
private Button findRouteButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
Intent intent = getIntent();
Geocoder coder = new Geocoder(this);
List<Address> addressList;
LatLng coord = null;
String completeAddress = intent.getStringExtra("completeAddress");
try {
addressList = coder.getFromLocationName(completeAddress, 5);
if (addressList != null) {
Address location = addressList.get(0);
coord = new LatLng(location.getLatitude(), location.getLongitude());
}
} catch (Exception ex) {
ex.printStackTrace();
}
mMap = googleMap;
MarkerOptions mMarkerOptions = new MarkerOptions();
mMarkerOptions.position(coord);
mMarkerOptions.title(completeAddress);
mMap.addMarker(mMarkerOptions).showInfoWindow();
mMap.moveCamera(CameraUpdateFactory.newLatLng(coord));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coord, 14.0f));
}
}
EDIT 1
I finally got the answer myself, on where to add, it was basically a minor error but just so other people know where to add I will update the answer here :
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private EditText findRouteEdittext;
private Button findRouteButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
findRouteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
searchString = findRouteEdittext.getText().toString().toLowerCase().trim();
if (searchString.equals("")){
// findRouteEditTextInputLayout.setErrorEnabled(true);
// findRouteEditTextInputLayout.setError("Enter a location or City!");
//use snackbar to show something.
}
else{
coder2 = new Geocoder(MapsActivity.this);
coord2 = null;
try {
addressList2 = coder2.getFromLocationName(searchString, 5);
if (addressList2 != null) {
Address location = addressList2.get(0);
coord2 = new LatLng(location.getLatitude(), location.getLongitude());
}
} catch (Exception ex) {
ex.printStackTrace();
}
if (coord2!=null && coord!=null) {
mMap.clear();
mMarkerOptions2 = new MarkerOptions();
mMarkerOptions2.position(coord2);
mMarkerOptions2.title(searchString); //this is the address of the new string entered by the user
mMap.addMarker(mMarkerOptions2).showInfoWindow();
mMarkerOptions3 = new MarkerOptions();
mMarkerOptions3.position(coord);
mMarkerOptions3.title(completeAddress); //this is the address of the original string received from intent
mMap.addMarker(mMarkerOptions3).showInfoWindow();
}
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
Intent intent = getIntent();
Geocoder coder = new Geocoder(this);
List<Address> addressList;
LatLng coord = null;
String completeAddress = intent.getStringExtra("completeAddress");
try {
addressList = coder.getFromLocationName(completeAddress, 5);
if (addressList != null) {
Address location = addressList.get(0);
coord = new LatLng(location.getLatitude(), location.getLongitude());
}
} catch (Exception ex) {
ex.printStackTrace();
}
mMap = googleMap;
MarkerOptions mMarkerOptions = new MarkerOptions();
mMarkerOptions.position(coord);
mMarkerOptions.title(completeAddress);
mMap.addMarker(mMarkerOptions).showInfoWindow();
mMap.moveCamera(CameraUpdateFactory.newLatLng(coord));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coord, 14.0f));
}
}
If you already got Location object then use below code to add new marker in to map.
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(latLng));
place this code in side add button on click listener.

No address showing on map click Android Google maps

Ive added reverse Geocoding to my map and set the map to clickable. Everything works as it should except the address is not showing above the marker when i click the map.
my latLan is an array but thats the only way it would allow me to use the variable. i think the problem lies around this area but cant put my hand on it.
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); // changes view to hybrid
mMap.setMyLocationEnabled(true); // shows location on map
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); // uses GPS only to get location
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
final LatLng[] latLng = {(new LatLng(currentLatitude, currentLongitude))};
mMap.animateCamera(
CameraUpdateFactory.newLatLngZoom(latLng[0], 18)); // This will zoom camera to updated lat and long without constant updates
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {// Setting a click event handler for the map
#Override
public void onMapClick(LatLng arg0) {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); // uses GPS only to get location
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
//LatLng latLng;
// Getting the Latitude and Longitude of the touched location
latLng[0] = arg0;
// Clears the previously touched position
mMap.clear();
// Animating to the touched position
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng[0]));
// Creating a marker
markerOptions = new MarkerOptions();
// Setting the position for the marker
markerOptions.position(latLng[0]);
// Placing a marker on the touched position
mMap.addMarker(markerOptions);
// Adding Marker on the touched location with address
new ReverseGeocodingTask(getBaseContext()).execute(latLng[0]);
}
});
//new ReverseGeocodingTask(getBaseContext()).execute(latLng);
}
private class ReverseGeocodingTask extends AsyncTask<LatLng, Void, String> {
Context mContext;
public ReverseGeocodingTask(Context context) {
super();
mContext = context;
}
#Override
protected String doInBackground(LatLng... params) {
Geocoder geocoder = new Geocoder(mContext);
double latitude = params[0].latitude;
double longitude = params[0].longitude;
List<android.location.Address> addresses = null;
String addressText = "";
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
if (addresses != null && addresses.size() > 0) {
android.location.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) {
markerOptions.title(addressText);
mMap.addMarker(markerOptions);
}
}
}
Tested your code and found possible cause of error.
// Placing a marker on the touched position
mMap.addMarker(markerOptions);
Upon implementing addMarker() before doing the ReverseGeocodingTask() and calling addMarker() again in the onPostExecute(). You can try adding an custom marker image large enough to make the address and the overwriting marker visible.
Customize the marker image
You can replace the default marker image with a custom marker image, often called an icon. Custom icons are always set as a BitmapDescriptor, and defined using one of four methods in the BitmapDescriptorFactory class.
Code for custom image:
private static final LatLng MELBOURNE = new LatLng(-37.813, 144.962);
private Marker melbourne = mMap.addMarker(new MarkerOptions()
.position(MELBOURNE)
.title("Melbourne")
.snippet("Population: 4,137,400")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.arrow)));
You can remove the first mMap.addMarker(markerOptions); before new ReverseGeocodingTask(getBaseContext()).execute(latLng[0]); then it your app will work as it should be.
Use This Code May be work for getting Address
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String addressLine = address.getAddressLine(0) + address.getAddressLine(1) + address.getAddressLine(2) + address.getAddressLine(3);
}

How to get an address from map in 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.

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

Categories

Resources