I am working on google map api v2. I have a button that adds marker to my current location.
Map can get my location right but sometimes (not every time) when i want to add marker to that location, marker goes far away from the blue dot.
I want to add my marker exactly on blue dot.
and this is my code for findMe button:
ImageButton findMyLocation_btn = (ImageButton) findViewById(R.id.findme);
if (findMyLocation_btn != null) {
findMyLocation_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
buildAlertMessageNoGps();
} else {
currentLocation = mMap.getMyLocation();
if ( marker1 == null && currentLocation != null) {
new onMyLocationClick().execute();
}
}
}
});
and onMyLocationClick()
private class onMyLocationClick extends AsyncTask{
#Override
protected Object doInBackground(Object[] params) {
Geocoder gc = new Geocoder(MainActivity.this);
List<Address> list = null;
try {
list = gc.getFromLocation(currentLocation.getLatitude(), currentLocation.getLongitude(), 1);
} catch (Exception ex) {
ex.printStackTrace();
}
if (list != null) {
add = list.get(0);
}
try {
origin = new LatLng(add.getLatitude(),add.getLongitude());
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute (Object o){
createMarker(add.getLatitude(), add.getLongitude(), add.getLocality(), add.getSubLocality());
}
}
Based on Google Maps doc:
This method was deprecated. use com.google.android.gms.location.FusedLocationProviderApi instead. FusedLocationProviderApi provides improved location finding and power usage and is used by the "My Location" blue dot.
The code to get current location is something like this:
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager
.getBestProvider(criteria, false));
double latitude = location.getLatitude();
double longitude = location.getLongitude();
For more advance solution you can use FusedLocationProvider as mentioned by google: https://developer.android.com/training/location/retrieve-current.html#GetLocation
Related
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).
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
}
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
I am trying to add multiple markers on GoogleMap. This is what I am doing:
private void initilizeMap() {
try {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager()
.findFragmentById(R.id.map)).getMap();
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
if (googleMap != null)
addMarkers();
// Getting LocationManager object from System Service
// LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria,
true);
// Getting Current Location
Location location = locationManager
.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
}
locationManager
.requestLocationUpdates(provider, 20000, 0, this);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
Following function adds markers:
private void addMarkers() {
try {
for (String title : locations.keySet()) {
if (locations.get(title).getLatitude() != 0
&& locations.get(title).getLongitude() != 0) {
// create marker
MarkerOptions marker = new MarkerOptions().position(
new LatLng(locations.get(title).getLatitude(),
locations.get(title).getLongitude()))
.title(title);
marker.icon(BitmapDescriptorFactory
.fromResource(R.drawable.pin_map));
// adding marker
googleMap.addMarker(marker);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
But markers are not displaying, though they are adding up on GoogleMap which I checked while debugging. No exception coming as well. I tried to change the icon image, still not working.
You are most probably using the old int values for latitude/longitude as they where expected for the GeoPoint of the previous GoogleMaps API. These are 1 million times too big for the new LatLng object, which expects double values rather than integers.
I have a timer.it is running every 5 minute.ı write a method called konumlarıAl in timer run method. this method get locations data from database.When konumlarıAl run,HaritaKonumGoster is method calling.I want to delete all markers and show new location data marker on map without refreshing page.
my code
private void HaritaKonumGoster() {
// TODO Auto-generated method stub
if (googleHarita == null) {
googleHarita = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.haritafragment))
.getMap();
if (googleHarita != null) {
googleHarita.clear();
if(mrks.size()!=0)
{
for (Marker marker: mrks) {
marker.remove();
}
mrks.clear();
}
googleHarita.setMyLocationEnabled(true);
LocationManager locationManager=(LocationManager)getSystemService(LOCATION_SERVICE);
Criteria criteria=new Criteria();
String provider =locationManager.getBestProvider(criteria, true);
Location mylocation=locationManager.getLastKnownLocation(provider);
double latitude=0;
double longitude=0;
double mylatitude=0;
double myLongtitude=0;
//double latitude=enlem;
//double longitude=boylam;
if (mylocation != null){
mylatitude=mylocation.getLatitude();
myLongtitude=mylocation.getLongitude();
}
BitmapDescriptor bitmapDescriptor
= BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN);
try{
for (int i = 0; i < degiskenler.taksici.size(); i++) {
latitude=Double.parseDouble(degiskenler.taksici.get(i).enlem.trim());
longitude=Double.parseDouble(degiskenler.taksici.get(i).boylam.trim());
LatLng istanbulKoordinat = new LatLng(latitude,longitude);
Marker m= googleHarita.addMarker(new MarkerOptions().position(istanbulKoordinat).title("Kız Kulesi").icon(bitmapDescriptor));
googleHarita.moveCamera(CameraUpdateFactory.newLatLngZoom(istanbulKoordinat, 7));
mrks.add(m);
// Toast.makeText(getBaseContext(),"harita :)",Toast.LENGTH_LONG).show();
}
}
catch(Exception exception) {
Toast.makeText(getBaseContext(),"harita olmadı",Toast.LENGTH_LONG).show();
}
googleHarita.addMarker(new MarkerOptions().position(new LatLng(mylatitude, myLongtitude)).title("you hereeee"));
}
}
}
location update every 5 minute method
private void LocationUpdateEvery5minute() {
// TODO Auto-generated method stub
zamanlayici = new Timer();
yardimci = new Handler(Looper.getMainLooper());
zamanlayici.scheduleAtFixedRate(new TimerTask()
{
#Override
public void run(){
yardimci.post(new Runnable()
{
public void run()
{ Toast.makeText(getBaseContext(), "timera girdi",Toast.LENGTH_SHORT).show();
konumlarıAl();
}
});
}
}, 0, ZAMAN);
}
Delete markers using
googleHarita.clear()
https://developer.android.com/reference/com/google/android/gms/maps/GoogleMap.html#clear()
Just one call to this method should be enough to remove all the markers on your map.
Then, and add markers using
googleHarita.addMarker()
http://developer.android.com/reference/com/google/android/gms/maps/model/Marker.html
example here
I don't think you need to refresh any pages.
You have to use map.clear(); which will help you to removes all markers, polylines, polygons, overlays, etc from the map.