I am trying to replace mMpap.SetMyPosition(true); function with my own. I had some success on it and when my custom image for "My Position Icon" is tapped, it moves camera to current location with my custom marker.
Everything works fine on it except whenever "My Position Icon" is tapped, it leaves a copy of marker to that position and moves to current location with a new marker.
I am fairly new to Android Development and looking for some help.
My code inside onCreate(Bundle savedInstanceState) is:
ImageView img = (ImageView) findViewById(R.id.myPostionButton);
img.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
getTheLocation();
}
});
And getTheLocation() is:
if (location != null) {
final double latitude = location.getLatitude();
final double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
final Marker marker = mMap.addMarker(
new MarkerOptions()
.position(new LatLng(latitude, longitude))
.draggable(true)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_marker)));
mMap.setTrafficEnabled(true);
mMap.setMinZoomPreference(10.0f);
mMap.setMaxZoomPreference(20.0f);
//mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16.0f),4000 , null);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16.0f));
mMap.setOnCameraMoveListener(new GoogleMap.OnCameraMoveListener() {
#Override
public void onCameraMove() {
LatLng centerOfMap = mMap.getCameraPosition().target;
marker.setPosition(centerOfMap);
}
});
mMap.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() {
#Override
public void onCameraIdle() {
LatLng centerOfMap = mMap.getCameraPosition().target;
marker.setPosition(centerOfMap);
double latitude = centerOfMap.latitude;
double longitude = centerOfMap.longitude;
Geocoder geocoder = new Geocoder(getApplicationContext());
try {
List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1);
String str = addressList.get(0).getAddressLine(0) + ", ";
str += addressList.get(0).getSubLocality() + ", ";
str += addressList.get(0).getLocality() + ", ";
str += addressList.get(0).getCountryCode();
mFromAddress.setText(str);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
And onMapReady(GoogleMap googleMap) is:
mMap = googleMap;
getTheLocation();
Please Help.
You can try any one of the following based on your situation:
1. If you have only one marker in map, before adding the new marker, clear the map using mMap.clear();
2. If you have multiple markers then you have to keep your current marker object as member variable mMarker. Then just before adding the new marker you can use mMarker.remove();.
Related
so i have a function
public void centerOnMapLocation (Location location, String title) {
if (location != null) {
LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
mMap.clear();
mMap.addMarker(new MarkerOptions().position(userLocation).title(title));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 13));
}
}
in android map activity and i implemented onMapLongClick(LatLng latLng)
#Override
public void onMapLongClick(LatLng latLng) {
String addressTitle = "";
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
try {
ArrayList<Address> addressArrayList = (ArrayList<Address>) geocoder.getFromLocation(latLng.latitude, latLng.latitude, 1);
if (addressArrayList != null & addressArrayList.size() > 0) {
if (addressArrayList.get(0).getAddressLine(0) != null) {
addressTitle += addressArrayList.get(0).getAddressLine(0);
}
}
} catch (IOException e) {
e.printStackTrace();
}
mMap.addMarker(new MarkerOptions().position(latLng).title(addressTitle));
}
in maps activity and inside the function i added a marker . but on long click the marker vanishes and when i remove
" mMap.clear() " from the previous function "centerOnMapLocation" then I'm able to add back the marker and it stays there .
My question is I'm not even calling that function in onMapLongClick but when i remove mMap.clear(); from the other function . I'm able to add markers inside it ?? What I'm doing wrong
I have designed a Marker and an Info Window. Now the location is being fetched from a Database every 2 seconds and the marker position gets updated. The Info Window is shown on Marker Click. Now whenever the marker gets updated, the Info Window disappears. If I put the Info Window inside repeat function then the Info Window keeps on showing. I need to show the Info Window on Marker Click and disappear on clicking Marker again. It should not disappear on the refreshing of Marker position.
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Log.e(TAG,"Getting Repeated Location");
scheduleSendLocation();
myLat = Double.parseDouble(latitude);
myLng = Double.parseDouble(longitude);
Toast.makeText(MapsActivity.this, "Lat:"+myLat+"\tLng:"+myLng, Toast.LENGTH_LONG).show();
if (myLat==0 && myLng==0) {
Toast.makeText(MapsActivity.this,"Invalid Location",Toast.LENGTH_SHORT).show();
handler.removeCallbacks(runnable);
Intent dev = new Intent(MapsActivity.this,DevicesNavActivity.class);
startActivity(dev);
}
else if (myLat==null && myLng==null) {
Toast.makeText(MapsActivity.this,"No Data Found",Toast.LENGTH_SHORT).show();
handler.removeCallbacks(runnable);
Intent dev = new Intent(MapsActivity.this,DevicesNavActivity.class);
startActivity(dev);
}
else {
CustomInfoWindowActivity customInfoWindow = new CustomInfoWindowActivity(this);
mMap.setInfoWindowAdapter(customInfoWindow);
final MarkerOptions markerOptions = new MarkerOptions();
final Marker[] m = new Marker[1];
LatLng loc = new LatLng(myLat,myLng);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(loc, 17f);
mMap.moveCamera(cameraUpdate);
handler.postDelayed(runnable2 = new Runnable() {
public void run() {
LatLng location = new LatLng(myLat, myLng);
//Adding Marker to Location
markerOptions.position(location)
.title("Marker")
.snippet("My Marker")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
myLat = Double.parseDouble(latitude);
myLng = Double.parseDouble(longitude);
mMap.clear();
m[0] = mMap.addMarker(markerOptions);
LatLng coordinate = new LatLng(myLat, myLng); //Store these lat lng values somewhere. These should be constant.
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(coordinate, 17f);
mMap.animateCamera(cameraUpdate);
handler.postDelayed(this, TIME);
}
}, TIME);
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
//Displaying the Info Window
InfoWindowData info = new InfoWindowData();
info.setName("Co-Ordinates of "+myimei);
info.setLatitude(latitude);
info.setLongitude(longitude);
m[0].setTag(info);
m[0].showInfoWindow();
return true;
}
});
after you add marker after clearing marker call showInfowindow on marker
m[0] = mMap.addMarker(markerOptions);
m[0].showInfoWindow();
this should do the trick
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);
}
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.
I am having trouble using the loactionListener in eclipse for android. I have been googling for a while now an I can't seem to see why this shouldn't work. The only thing I can think of is that maybe it is because my testing device has no sim. (the internet is provided via wifi).
I have used this as a reference and still, nothing.
Could anyone help me with this problem.
here is the relevant parts of my activity:
public class MainMenu extends Activity implements LocationListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu);
theMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.the_map)).getMap();
theMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
locMan = (LocationManager)getSystemService(LOCATION_SERVICE);
}
#Override
public void onLocationChanged(Location location) {
final Double lat = location.getLatitude();
final Double lng = location.getLongitude();
LatLng lastLatLng = new LatLng(lat, lng);
String title = getString(new StringLang().textSet(userLang,"marker_title"));
String snippit = getString(new StringLang().textSet(userLang,"marker_snip"));
if(userMarker!=null) userMarker.remove();
userMarker = theMap.addMarker(new MarkerOptions()
.position(lastLatLng)
.title(title)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher))
.snippet(snippit));
reverseGeoCode(lat, lng);
}
}
I was using a different method to display my location on the map, which worked well but it never updated. It always showed my location at the last place I used the GPS, which turns out was 60mile accross the country. I can see this is working but is there a better way of doing this.
Old method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu);
if(findViewById(R.id.the_map) != null){
//map has loaded continue
theMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.the_map)).getMap();
theMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
android.location.Location lastLoc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
LatLng lastLatLng ;
if(lastLoc == null){
/* Use the LocationManager class to obtain GPS locations */
double latitude = 0;
double longitude = 0;
lastLatLng = new LatLng(latitude, longitude);
lat = latitude;
lng = longitude;
String title = getString(new StringLang().textSet(userLang,"marker_title"));
String snippit = getString(new StringLang().textSet(userLang,"marker_snip"));
if(userMarker!=null) userMarker.remove();
userMarker = theMap.addMarker(new MarkerOptions()
.position(lastLatLng)
.title(title)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.your_loc_icon))
.snippet(snippit));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(lastLatLng) // Sets the center of the map to user position
.zoom(0) // Sets the zoom
.bearing(90) // Sets the orientation of the camera to east
.tilt(20) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
currentLoc = lastLatLng;
theMap.animateCamera (CameraUpdateFactory.newCameraPosition(cameraPosition), 3000, null);
final TextView geoTagText = (TextView)findViewById(R.id.text_geoTag);
geoTagText.setText("We cannot find your current location, please check your settings.");
}else{
double latitude = lastLoc.getLatitude();
double longitude = lastLoc.getLongitude();
lastLatLng = new LatLng(latitude, longitude);
lat = latitude;
lng = longitude;
animateMap(lastLatLng);
}
}else{
theMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.the_map)).getMap();
theMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
android.location.Location lastLoc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
LatLng lastLatLng;
double latitude = lastLoc.getLatitude();
double longitude = lastLoc.getLongitude();
lastLatLng = new LatLng(latitude, longitude);
lat = latitude;
lng = longitude;
animateMap(lastLatLng);
//no map to load
}
}
#Override
public void onLocationChanged(Location location) {
final Double lat = location.getLatitude();
final Double lng = location.getLongitude();
LatLng lastLatLng = new LatLng(lat, lng);
String title = getString(new StringLang().textSet(userLang,"marker_title"));
String snippit = getString(new StringLang().textSet(userLang,"marker_snip"));
if(userMarker!=null) userMarker.remove();
userMarker = theMap.addMarker(new MarkerOptions()
.position(lastLatLng)
.title(title)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher))
.snippet(snippit));
}
it would also be useful to add that there is button to relocate the user manually if they want.
reLocBtn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
if(menuActive == true){
playSound();
LocationManager loc = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
android.location.Location gpsLoc = (Location) loc.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double lat = gpsLoc.getLatitude();
double lng = gpsLoc.getLongitude();
LatLng lastLatLng = new LatLng(lat, lng);
animateMap(lastLatLng);
}
}
});
I'm not to sure why either method doesn't update, but the second method seams to work better on first load.
You don't appear to be using requestLocationUpdates() anywhere. In that method you pass a LocationListener object that it then calls for location updates.
i.e. in your case:
locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
If you are using Google Maps API v2, you can do it using that, for example:
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
mMarker = mMap.addMarker(new MarkerOptions().position(loc));
if(mMap != null){
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
}
}
};
and then set the listener for the map:
mMap.setOnMyLocationChangeListener(myLocationChangeListener);
This will get called when the map first finds the location.
No need for LocationService or LocationManager at all.