map with default marker that is never set
In the middle of the map there is a marker, which is always shown on this location when I start the activity with the map fragment in it. But I never set this marker... Does someone know why this is and maybe how I can delete this marker?
Here is my code:
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
int permissionCheck = ContextCompat.checkSelfPermission(MapsActivity.this,
android.Manifest.permission.ACCESS_FINE_LOCATION);
if(permissionCheck == PackageManager.PERMISSION_GRANTED){
getCurrentLocation();
onSearch();
}else if(permissionCheck == PackageManager.PERMISSION_DENIED){
onSearch();
}
}
//gets current location of the user.
public void getCurrentLocation() {
double lat = 0;
double lng = 0;
try {
mMap.setMyLocationEnabled(true); //allows query of current location.
}catch(SecurityException e){
e.printStackTrace();
}
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Geocoder geocoderGetAddress = new Geocoder(MapsActivity.this);
try{
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location!=null) {
lat = location.getLatitude();
lng = location.getLongitude();
}
}catch(SecurityException e){
e.printStackTrace();
}
//the rest of this method gets the address from the geocoder, so that it can be displayed as a String on the marker info window.
String displayAddress ="";
try {
List<Address> currAddress = geocoderGetAddress.getFromLocation(lat, lng, 1);
if(currAddress.size() >0){
for(int i=0; i<currAddress.get(0).getMaxAddressLineIndex();i++){
displayAddress += currAddress.get(0).getAddressLine(i) +"\n";
}
}
}catch (IOException e){
e.printStackTrace();
}
mMap.addMarker(new MarkerOptions().position(new LatLng(lat,lng)).title(myLoc).snippet(displayAddress));
LatLng myLatLng = new LatLng(lat, lng);
mMap.animateCamera(CameraUpdateFactory.newLatLng(myLatLng));
initAcceptButton();
}
Thanks!
I just solved the problem with adding
if(lat!= 0 || lng != 0){
//add marker here
}
Related
I am working in a app with maps, in the first activity I have a NavigationDrawer with differents fragments, in one of them I get the last Location every 10 seconds and with it set a TextView with the address of that location. Everything was going perfect since I create a new Activity for details of a Place with a MapView and when you put a Marker it get its address, but it always return null I don´t know why..
There is my code.
1rst Activity with Fragment
public void setLocationListeners() {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_PERMISSION_LOCATION);
} else {
mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
Location lastLocation = locationResult.getLastLocation();
Address address = getAddress(lastLocation.getLongitude(), lastLocation.getLatitude(), getContext());
myLocation = new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude());
if (address == null) {
((TextView) mView.findViewById(R.id.txtVosEstas)).setText(String.valueOf(
lastLocation.getLongitude() + " " + lastLocation.getLatitude()));
} else
((TextView) mView.findViewById(R.id.txtVosEstas)).setText(address.getAddressLine(0).split(",")[0]);
((TextView) mView.findViewById(R.id.txtBearing)).setText(String.valueOf(lastLocation.getBearing()));
((TextView) mView.findViewById(R.id.txtVelocidad)).setText(String.valueOf(lastLocation.getSpeed()));
}
};
}
}
"getAddress" is the static method in my MapHelper
public static Address getAddress(double lng, double lat, Context c) {
Geocoder geocoder = new Geocoder(c, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
return addresses.get(0);
} catch (IOException e) {
e.printStackTrace();
} catch (IndexOutOfBoundsException e) {
}
return null;
}
I call the same method in the other Activity when the map is ready.
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng latLng) {
mMap.clear();
mMap.addMarker(new MarkerOptions().position(latLng));
String lat = String.format("%.7f", latLng.latitude);
String lng = String.format("%.7f", latLng.longitude);
((TextView) findViewById(R.id.txtLat)).setText(lat);
((TextView) findViewById(R.id.txtLng)).setText(lng);
Address address = getAddress(Double.valueOf(lat), Double.valueOf(lng), getApplicationContext());
((MultiAutoCompleteTextView) findViewById(R.id.txtDireccion)).setText(address != null? address.getAddressLine(0) : "Sin dirección");
}
});
if (mLugar != null){
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mLugar.getLatLng(), 15));
MarkerOptions marker = new MarkerOptions()
.position(mLugar.getLatLng())
.title(mLugar.getNombre());
mMap.addMarker(marker);
}
}
And in it I never get results.
I am developing an android google map application, that is showing current location on map starting.
I have an search bar in the application, when user enter any area name, then the second marker will be placed on that location.
Now my problem is, how to get second marker longitude and latitude position and make a route between the two markers.
my MainActivity.java code as follows:
public class MainActivity 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);
}
public void onMapSearch(View view) {
EditText locationSearch = (EditText) findViewById(R.id.editText);
String location = locationSearch.getText().toString();
List<Address> addressList = null;
if (location != null || !location.equals("")) {
Geocoder geocoder = new Geocoder(this);
try {
addressList = geocoder.getFromLocationName(location, 1);
} catch (IOException e) {
e.printStackTrace();
}
Address address = addressList.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title("Marker"));
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(27.746974, 85.301582);
mMap.addMarker(new MarkerOptions().position(sydney).title("Kathmandu, Nepal"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
// Enable MyLocation Button in the Map
mMap.setMyLocationEnabled(true);
}
}
Please Help me.
In your program you have used the code to get the LatLng of the second marker.
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title("Marker"));
To make a polyline, refer to this link. By the this question has already been answered.
https://www.simplifiedcoding.net/google-maps-distance-calculator-google-maps-api/
Set Google Places API for search EdiText. Get the value from that and pass it as address..
Here is the code(address denoting strAddress here)
List<Address> address = null;
Geocoder coder = new Geocoder(getApplicationContext());
try {
address = coder.getFromLocationName(strAddress, 1);
} catch (IOException e) {
e.printStackTrace();
}
if (address != null) {
Address location = address.get(0);
double lat = location.getLatitude();
double log = location.getLongitude();
}
Iam getting Every Minute LatLong from Shared preferences, Showing on Map.
Marker is Moving Perfectly in Every minute, but not removing the Old marker(Its Showing Every Minute New Marker.
But closing and Opening the map fragment its showing Single Marker Perfectly.
Please Help me how to fix this.also i tried Marker.Remove
I called below method inside OnLocation Changed Method.
/*
Method to display the location on UI
*/
private void displayLocation()
{
try
{
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null)
{
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
// get user data from session
HashMap<String, String> user = session.getGPSPING();
// UserLat
String LatLongUser="";
LatLongUser = user.get(SessionManagerFor_Register.KEY_LATLONG);
if(!LatLongUser.equals(""))
{
Log.i(" PING on MAP LatLong", LatLongUser);
String[] LanlongArr = LatLongUser.split("//");
List<String> Lanlonglist1 = Arrays.asList(LanlongArr);
int length = Lanlonglist1.size();
arraylist_DetailLineWalker = new ArrayList<String(length);
for (int i = 0; i < length; i++)
{
arraylist_DetailLineWalker.add(Lanlonglist1.get(i));
}
if(arraylist_DetailLineWalker!=null)
{
for (int i = 0; i < arraylist_DetailLineWalker.size(); i++)
{
try {
String Val = arraylist_DetailLineWalker.get(i).toString();
//Log.i(" Validation Id",Val);
VALUE_ARRAY_STRING = Val.toString().split("::");
LatLong_DataSaveTable = VALUE_ARRAY_STRING[0].toString();
System.out.println("checking STarted" + LatLong_DataSaveTable);
String[] latlong = LatLong_DataSaveTable.split(",");
double latitude1 = Double.parseDouble(latlong[0]);
double longitude2 = Double.parseDouble(latlong[1]);
//To hold location
LatLng latLng1 = new LatLng(latitude1, longitude2);
//To create marker in map
MarkerOptions markerOptionsLineWalker = new MarkerOptions();
markerOptionsLineWalker.position(latLng1); //setting position
markerOptionsLineWalker.draggable(true); //Making the marker draggable
markerOptionsLineWalker.title("Walker Location");
markerOptionsLineWalker.icon(BitmapDescriptorFactory.fromResource(R.drawable.walker_outof_fence_icon_red));
Marker marker1 = googleMap.addMarker(markerOptionsLineWalker);
if (marker1 != null)
{
marker1.remove();
}
//adding marker to the map
googleMap.addMarker(markerOptionsLineWalker);
// marker1.setPosition(latLng1);
Log.i(TAG, "Walker PING Added.............................");
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
}
else
{
Log.i("MAP NEwLatLong","TOTAL ARRY LIST NULLL");
}
}
else
{
Log.i("MAP NEwLatLong","Null Not LatLong");
}
}
else
{
Log.i("Location EXception","Couldn't get the location. Make sure location is enabled on the device");
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Try this....
Marker now;
#Override
public void onLocationChanged(Location location) {
if(now != null){
now.remove(); //if the marker is already added then remove it
}
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
now = googleMap.addMarker(new MarkerOptions().position(latLng)));
}
For Reference, visit this...
https://stackoverflow.com/a/16312869/6385873
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 have been googling this for hours but no luck so far.
I want to get the address of the location where the map is touched / tapped.
I understand that in order to get the address i need to reverse geocode the coordinates. But how do i get the coordinates from the map in the first place?
All you need to do is set up a OnMapClickListener, and then the onMapClick() override will give you a LatLng object. Then, use a Geocoder object to get the address of the point that was just clicked on.
In this simple example, I've also added a Marker every time the user clicks a new point on the map.
Here is the main piece of functionality that you need:
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
//save current location
latLng = point;
List<Address> addresses = new ArrayList<>();
try {
addresses = geocoder.getFromLocation(point.latitude, point.longitude,1);
} catch (IOException e) {
e.printStackTrace();
}
android.location.Address address = addresses.get(0);
if (address != null) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < address.getMaxAddressLineIndex(); i++){
sb.append(address.getAddressLine(i) + "\n");
}
Toast.makeText(MapsActivity.this, sb.toString(), Toast.LENGTH_LONG).show();
}
//remove previously placed Marker
if (marker != null) {
marker.remove();
}
//place marker where user just clicked
marker = mMap.addMarker(new MarkerOptions().position(point).title("Marker")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)));
}
});
Here is the full class that I used to test this:
public class MapsActivity extends AppCompatActivity {
private GoogleMap mMap;
private LatLng latLng;
private Marker marker;
Geocoder geocoder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
geocoder = new Geocoder(this, Locale.getDefault());
setUpMapIfNeeded();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.setMyLocationEnabled(true);
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
mMap.getUiSettings().setMapToolbarEnabled(false);
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
//save current location
latLng = point;
List<Address> addresses = new ArrayList<>();
try {
addresses = geocoder.getFromLocation(point.latitude, point.longitude,1);
} catch (IOException e) {
e.printStackTrace();
}
android.location.Address address = addresses.get(0);
if (address != null) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < address.getMaxAddressLineIndex(); i++){
sb.append(address.getAddressLine(i) + "\n");
}
Toast.makeText(MapsActivity.this, sb.toString(), Toast.LENGTH_LONG).show();
}
//remove previously placed Marker
if (marker != null) {
marker.remove();
}
//place marker where user just clicked
marker = mMap.addMarker(new MarkerOptions().position(point).title("Marker")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)));
}
});
}
}
Result of tapping the map in two different points:
Google Map has callbacks to do that like this one or this one.
Just implement them in your code and as soon as they're fired, just make a reverse geocode the coordinates. You actually found the most complicated part (you understood that you need to reverse geocode).