Google map V2 giving the address of previous touched location - android

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

Related

how to use polyline in google maps in android?

public class map2 extends AppCompatActivity implements OnMapReadyCallback, GoogleMap.OnMyLocationChangeListener {
private static final String TAG =null ;
private GoogleMap mGoogleMap;
private Geocoder mGeocoder;
String Startlongitude,Endlongitude;
String Startlattitude,Endlattitude;
double lon,Eat,Elot;
double lat;
LatLng latlon,latlon2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
SupportMapFragment mSupportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mSupportMapFragment.getMapAsync(this);
mGeocoder = new Geocoder(this, Locale.getDefault());
Bundle b = getIntent().getExtras();
String Array=b.getString("ITEM_EXTRA");
String Tripname = getIntent().getExtras().getString("Trip");
List<LatLng> routeArray = new ArrayList<>();
try {
JSONArray jO=new JSONArray(Array);
for(int i=0;i<jO.length();i++)
{
JSONObject tripObject=jO.getJSONObject(i);
String Trips=tripObject.getString("TripNO");
JSONObject msg=tripObject.getJSONObject("Trips");
if(Trips.equals(Tripname))
{
JSONArray msgObject=msg.getJSONArray("Trip1");
for(int j=0;j<msgObject.length();j++)
{
JSONObject d=msgObject.getJSONObject(j);
Startlongitude=d.getString("SfltLogitude");
Startlattitude=d.getString("Sfltlattitude");
Endlongitude = d.getString("EfltLogitude");
Endlattitude = d.getString("Efltlattitude");
Eat=Double.parseDouble(Endlattitude.trim());
Elot=Double.parseDouble(Endlongitude.trim());
lat=Double.parseDouble(Startlattitude.trim());
lon=Double.parseDouble(Startlongitude.trim());
latlon= new LatLng(lat, lon);
latlon2=new LatLng(Eat,Elot);
PolylineOptions polyLineOptions = new PolylineOptions();
polyLineOptions.addAll(latlon,latlon2);
polyLineOptions.width(2);
polyLineOptions.color(Color.BLUE);
mGoogleMap.addPolyline(polyLineOptions);
break;
}
}
else{
String task=tripObject.getString("Trips");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.normal:
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
break;
case R.id.satellite:
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
break;
case R.id.terrain:
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
break;
case R.id.hybrid:
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
break;
case R.id.none:
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NONE);
break;
}
return true;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.setOnMyLocationChangeListener(this);
}
#Override
public void onMyLocationChange(Location location) {
}
}
here i have fetch LAttitude and Longitude from JsonServer and also converted it into doubles......but iam unable to plot the path in google map??..IT is showing me this ERROR" Polyline com.google.android.gms.maps.GoogleMap.addPolyline(com.google.android.gms.maps.model.PolylineOptions)' on a null object reference"
You are setting polyline on the map when map is not yet ready. So move you code of setting polyline in onMapReady() method.
Like :
public class map2 extends AppCompatActivity implements OnMapReadyCallback, GoogleMap.OnMyLocationChangeListener {
private static final String TAG =null ;
private GoogleMap mGoogleMap;
private Geocoder mGeocoder;
String Startlongitude,Endlongitude;
String Startlattitude,Endlattitude;
double lon,Eat,Elot;
double lat;
LatLng latlon,latlon2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
SupportMapFragment mSupportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mSupportMapFragment.getMapAsync(this);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.normal:
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
break;
case R.id.satellite:
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
break;
case R.id.terrain:
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
break;
case R.id.hybrid:
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
break;
case R.id.none:
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NONE);
break;
}
return true;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.setOnMyLocationChangeListener(this);
mGeocoder = new Geocoder(this, Locale.getDefault());
Bundle b = getIntent().getExtras();
String Array=b.getString("ITEM_EXTRA");
String Tripname = getIntent().getExtras().getString("Trip");
List<LatLng> routeArray = new ArrayList<>();
try {
JSONArray jO=new JSONArray(Array);
for (int i = 0; i < jO.length(); i++)
{
JSONObject tripObject=jO.getJSONObject(i);
String Trips = tripObject.getString("TripNO");
JSONObject msg = tripObject.getJSONObject("Trips");
if (Trips.equals(Tripname))
{
JSONArray msgObject=msg.getJSONArray("Trip1");
for (int j = 0; j < msgObject.length(); j++)
{
JSONObject d = msgObject.getJSONObject(j);
Startlongitude = d.getString("SfltLogitude");
Startlattitude = d.getString("Sfltlattitude");
Endlongitude = d.getString("EfltLogitude");
Endlattitude = d.getString("Efltlattitude");
Eat=Double.parseDouble(Endlattitude.trim());
Elot=Double.parseDouble(Endlongitude.trim());
lat = Double.parseDouble(Startlattitude.trim());
lon = Double.parseDouble(Startlongitude.trim());
latlon = new LatLng(lat, lon);
latlon2 = new LatLng(Eat,Elot);
PolylineOptions polyLineOptions = new PolylineOptions();
polyLineOptions.addAll(latlon,latlon2);
polyLineOptions.width(2);
polyLineOptions.color(Color.BLUE);
mGoogleMap.addPolyline(polyLineOptions);
break;
}
}
else {
String task = tripObject.getString("Trips");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onMyLocationChange(Location location) {
}
}

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

Google map not display Marker

hi i have to implement Google map v2 in my application an it's perfect working. but my problem i have to send one Marker position from one activity to another activity and then add marker into Google map but i don't know it's not.
Post my code below.
public class BasicMapActivity extends FragmentActivity{
private GoogleMap mMap;
AlertMessages messages;
String latitude;
double lat = 0, lng = 0;
String longitude ;
String title = "", city = "";
static boolean is_back_pressed = false;
ImageView img;
GPSTracker gps;
RelativeLayout rel;
Marker Contactloc;
LatLng contactLoc;
Button ib_back;
static boolean is_window_pressed = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basic_demo_new);
img = (ImageView) findViewById(R.id.popup_h);
img.setVisibility(View.INVISIBLE);
gps = new GPSTracker(getParent());
messages = new AlertMessages(getParent());
Bundle b = getIntent().getExtras();
title = b.getString("title");
city = b.getString("City");
latitude = b.getString("latitude");
longitude = b.getString("longitude");
back_layout=(LinearLayout)findViewById(R.id.back_lay);
ib_back=(Button)findViewById(R.id.ib_back_music);
System.out.println("Lat:::" + latitude);
System.out.println("Long:::" + longitude);
setUpMapIfNeeded();
ib_back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
is_back_pressed = true;
TabGroupActivity parentActivity = (TabGroupActivity) getParent();
parentActivity.onBackPressed();
}
});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
try{
System.out.println("Map Pause state");
if(mMap!=null){
mMap.clear();
mMap=null;
TabGroupActivity parentActivity = (TabGroupActivity) getParent();
parentActivity.onBackPressed();
}
}catch(Exception e){
e.printStackTrace();
}
}
#Override
protected void onResume() {
super.onResume();
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getParent());
if (status == ConnectionResult.SUCCESS) {
setUpMapIfNeeded();
mMap.setMyLocationEnabled(true);
} else {
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, getParent(),
requestCode);
dialog.show();
}
}
protected LocationManager locationManager;
LatLng pos=null;
private void setUpMapIfNeeded() {
System.out.println("Setup If Needed");
// Do a null check to confirm that we have not already instantiated the
// map.
if (mMap == null) {
mMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map1)).getMap();
mMap.setMyLocationEnabled(true);
boolean isInternetPresent = isConnectingToInternet();
if (!isInternetPresent) {
// Internet Connection is not present
Toast.makeText(getParent(), "Internet Connection Error!",Toast.LENGTH_SHORT).show();
//messages.showAlertDialog(getParent(),
// "Internet Connection Error",
//"Please connect to working Internet connection");
// stop executing code by return
// return;
} else {
locationManager = (LocationManager) getParent()
.getSystemService(LOCATION_SERVICE);
// getting GPS status
if (!locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
showSettingsAlert();
}
if (gps.canGetLocation()) {
lat = gps.getLatitude();
lng = gps.getLongitude();
pos = new LatLng(lat, lng);
if (lat == 0.0 && lng == 0.0) {
Toast.makeText(getParent(), "Can't find location",
Toast.LENGTH_SHORT).show();
} else {
mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.mark_blue))
.position(pos)
.title("Current Location"));
double trans = 0.3;
for (int k = 100; k <= 500;) {
// draw circle
int radiusM = k;
int d = k; // diameter
Bitmap bm = Bitmap.createBitmap(d, d,
Config.ARGB_8888);
Canvas c = new Canvas(bm);
Paint p = new Paint();
p.setColor(getResources().getColor(
android.R.color.darker_gray));
c.drawCircle(d / 2, d / 2, d / 2, p);
// generate BitmapDescriptor from circle
// Bitmap
BitmapDescriptor bmD = BitmapDescriptorFactory
.fromBitmap(bm);
// mapView is the GoogleMap
mMap.addGroundOverlay(new GroundOverlayOptions()
.image(bmD)
.position(pos, radiusM * 2,
radiusM * 2)
.transparency((float) trans));
k = k + 100;
trans = trans + 0.1;
}
}
} else {
Toast.makeText(getParent(), "Can't find location",
Toast.LENGTH_SHORT).show();
}
}
mMap.getUiSettings().setCompassEnabled(true);
mMap.setTrafficEnabled(true);
mMap.getUiSettings().setTiltGesturesEnabled(true);
mMap.getUiSettings().setRotateGesturesEnabled(true);
mMap.getUiSettings().setScrollGesturesEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setZoomGesturesEnabled(true);
setUpMap();
} // Check if we were successful in obtaining the map.
if (mMap != null) {
mMap.setMyLocationEnabled(true);
setUpMap();
}
}
private void setUpMap() {
System.out.println("Setup Map");
try{
contactLoc=new LatLng(latitude, longitude);
Contactloc=mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.mark_red))
.position(new LatLng(latitude, longitude)).title(title)
.snippet(city));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
latitude, longitude), 18.0f));
}catch(Exception ew){
ew.printStackTrace();
}
}
}
please some one help me!
Add Marker like below
Contactloc=mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.mark_red))
.position(new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude)).title(title)
.snippet(city));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
latitude, longitude), 18.0f));
You need to Convert your latitude and longitude String values into Double. and AFAIK you said no not any error. your app defiantly crash over here with some logcat.

Categories

Resources