How to implement adding a marker on long press in Google Maps API v3 for android? There are answers about this in Stack Overflow itself but they are for Google Maps API v2.
public class advertiserMap extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_advertiser_map);
// 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);
}
//for searching for a location
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.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(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
As #tyczj pointed out, there's no v3 for Android Google Maps API, so you are probably using v2.
That said, to accomplish what you want, call setOnMapLongClickListener in your mMap object, and add the marker as you want inside onMapLongClick. You should do this in the onMapReady method:
#Override
public void onMapReady(GoogleMap googleMap) {
...
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng latLng) {
googleMap.addMarker(new MarkerOptions()
.position(latLng)
.title("Your marker title")
.snippet("Your marker snippet"));
}
});
}
// EDIT:
If you want to keep only one marker present at a time, you should declare your marker in the global activity's scope, and then, in onMapLongClick, if marker already exists, instead of creating a new marker, just update it's position:
public class advertiserMap extends FragmentActivity implements OnMapReadyCallback {
// Declare marker globally
Marker myMarker;
...
#Override
public void onMapReady(GoogleMap googleMap) {
...
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng latLng) {
// First check if myMarker is null
if (myMarker == null) {
// Marker was not set yet. Add marker:
myMarker = googleMap.addMarker(new MarkerOptions()
.position(latLng)
.title("Your marker title")
.snippet("Your marker snippet"));
} else {
// Marker already exists, just update it's position
myMarker.setPosition(latLng);
}
}
});
}
}
If done like this, remember to always check if your marker is not NULL before manipulating it in your code.
Hey guys if you all are using mMap.clear() then remove it . Mostly it work just fine.
Related
public class Returnmapdet extends FragmentActivity implements OnMapReadyCallback,GoogleMap.OnMapLongClickListener,GoogleMap.OnCameraMoveListener,GoogleMap.OnMapClickListener {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_returnmapdet);
// 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);
/* String[] latLng = "-34.8799074,174.7565664".split(",");
double latitude = Double.parseDouble(latLng[0]);
double longitude = Double.parseDouble(latLng[1]);
LatLng location = new LatLng(latitude, longitude);*/
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
#Override
public void onMapLongClick(LatLng point) {
mMap.addMarker(new MarkerOptions()
.position(point)
.title("You are here")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
}
#Override
public void onCameraMove() {
mMap.setOnCameraMoveListener(this);
}
#Override
public void onMapClick(LatLng latLng) {
mMap.setOnMapClickListener(this);
Toast.makeText(getApplicationContext(), "tha",
Toast.LENGTH_LONG).show();
}
}
when i launch the map and when i click the map it doesn't toasting me any thing.
Set onClickListener on Map object inside onMapReady
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
mMap.setOnMapClickListener(this);
mMap.setOnMapLongClickListener(this);
}
remove mMap.setOnMapClickListener(this); from onMapClick method, its unnecessary.
Happy Coding.
you implement your interface but you should add this code
mMap.setOnMapLongClickListener(this);
mMap.setOnCameraMoveListener(this);
mMap.setOnMapClickListener(this);
to add callback to your activity.
goodluck
First, I plot a Marker like this:
public void addMarker(String title,String lat,String Lng,int id,String address,int f)
{
marker= mMap.addMarker(new MarkerOptions().snippet(title)
.title(title+", "+address)
.position(new LatLng(Double.valueOf(lat), Double.valueOf(Lng)))
.icon(BitmapDescriptorFactory.fromResource(id)));
LatLng coordinate = new LatLng(Double.valueOf(lat), Double.valueOf(Lng));
CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 10);
mMap.animateCamera(yourLocation);
mMarkerArray.add(marker);
}
After that I am trying to replace the Marker with another icon when ever I reached at any existing Location
#Override
public void onLocationChanged(Location location)
{
Log.d("latitude_main", "onlocation???");
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Log.e("latitude_main", "latitude--" + latitude+"longitude="+longitude);
current_lat= String.valueOf(latitude);
current_lng= String.valueOf(longitude);
Log.e("latitude_main","size-=="+salesmanlocationArrayList.size() );
for(int i=0;i<salesmanlocationArrayList.size();i++)
{
if(salesmanlocation.getLati().equals("12.9165757") && salesmanlocation.getLongi().equals("77.6101163"))
{
mMap.addMarker(new MarkerOptions()
.snippet(""+i).title(salesmanlocation.getFirm_name()+", "+salesmanlocation.getAddress())
.position(new LatLng(Double.valueOf(salesmanlocation.getLati().toString()), Double.valueOf(salesmanlocation.getLongi().toString())))
.icon(BitmapDescriptorFactory.fromResource(R.drawable.event_events_select)));
}
mapFragment.getMapAsync(this);
}
}
I want to remove the marker from the map when the user visits that location.
You can simply define one OnMyLocationChangeListener class that performs your tasks, and set it on your GoogleMap instance, this way you can use it whenever you want in your application.
Step 1 - define your listener
public class MyMarkerLocationListener implements GoogleMap.OnMyLocationChangeListener {
List<Marker> markerList;
int MY_DISTANCE;
GoogleMap mMap;
public MyMarkerLocationListener(List<Marker> markerList, int meters, GoogleMap mMap)
{
this.markerList = markerList;
this.MY_DISTANCE = meters;
this.mMap = mMap;
}
#Override
public void onMyLocationChange(Location location) {
// your code/logic
//...
Location myNewLocation = location;
Location someMarkerLocation = new Location("some location");
//for each marker on your list
//check if you are close to it
for (Marker m : markerList) {
LatLng markerPosition = m.getPosition();
someMarkerLocation.setLatitude(markerPosition.latitude);
someMarkerLocation.setLongitude(markerPosition.longitude);
if (myNewLocation.distanceTo(someMarkerLocation) < MY_DISTANCE) {
//remove marker
m.remove();
//or if you still want to use it later
//m.setVisible(false);
// add your new marker
//mMap.addMarker(new MarkerOptions().icon()....);
}
}
}
}
After defining your class you just set the listener on your map on your fragment or activity code =)
Step 2 - instanciate the listener and set it
MyMarkerLocationListener myListener = new MyMarkerLocationListener(mMarkerArray, 100, mMap);
mMap.setOnMyLocationChangeListener(myListener);
UPDATE to answer your question in the comments:
You should initialize mMap before using it, take a look at this piece of code from this Stackoverflow question
public class MapPane extends Activity implements OnMapReadyCallback {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_activity);
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap map) {
//DO WHATEVER YOU WANT WITH GOOGLEMAP
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
map.setMyLocationEnabled(true);
map.setTrafficEnabled(true);
map.setIndoorEnabled(true);
map.setBuildingsEnabled(true);
map.getUiSettings().setZoomControlsEnabled(true);
}
}
don't forget your activity should implement the OnMapReadyCallback interface so the onMapReady method is called
you can use the map only after it is ready
Hope this helps!
I made a code.
In this code, when i click a map, there will be a marker on clicked point.
This is my Code
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(final GoogleMap googleMap) {
mMap = googleMap;
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
} else {
Toast.makeText(getApplicationContext(), "oh, no", Toast.LENGTH_LONG).show();
}
googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
String lat = String.valueOf(point.latitude);
String lng = String.valueOf(point.longitude);
MarkerOptions marker = new MarkerOptions().position(
new LatLng(point.latitude, point.longitude)).title("ok");
mMap.addMarker(marker);
}
});
}
}
Question :
What i want is that when i click SetMylocationEnable button, there also added a new marker. And because i want marker is only one in whole map, another marker that has been in the map before is to be removed. How can i do it? Would you teach me?
You can see what button i saying is, in picture. (picture is from : Enable my location icon Googlemap v2)
mMap.setOnMyLocationButtonClickListener(new OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick() {
Location location = getLocation();
MarkerOptions marker = new MarkerOptions().position(
new LatLng(location.getLatitude(), location.getLongitude())).title("ok");
mMap.addMarker(marker);
return true;
}
});
private Location getLocation() {
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
return locationManager.getLastKnownLocation(locationManager
.getBestProvider(criteria, false));
}
keep a reference to the marker, if the reference is null then create the marker as you have done, if it is not, then edit the marker and change its location
I new in coding google map,
my question is how i control the user gestur drag , zoom in and zoom out.
because my code always back to the current location of user when i zoomin/out, nad when i drag/ scroll up, down, left, right. always back to the current possition .
its my code for current loc user
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));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16));
}
};
You can use a boolean to move the camera only the first time:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMyLocationChangeListener {
private GoogleMap mMap;
private Marker mMarker;
private boolean firstTime = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationChangeListener(this);
}
#Override
public void onMyLocationChange(Location location) {
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
mMarker = mMap.addMarker(new MarkerOptions().position(loc));
if (firstTime) {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16));
firstTime = false;
}
}
}
NOTE: Take into account that this example uses GoogleMap.OnMyLocationChangeListener only because that is the method that you are using in your question, but it's deprecated and you must use the FusedLocationProviderApi according to the documentation:
public final void setOnMyLocationChangeListener
(GoogleMap.OnMyLocationChangeListener listener)
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. See the
MyLocationDemoActivity in the sample applications folder for example
example code, or the Location Developer Guide.
I am trying to add a marker all depending on what activity the user is on. For example, if the user is in the location1 activity and clicks the button to open maps, it should open Google Maps with a marker at where location1 is. Alternatively, if the user is in the location2 activity and clicks the button to open maps, it should open Google Maps with a marker at where location 2 is.
I have it working when they click on one activity, it brings them to Google Maps and has a marker at where that location is. I have simply tried to copy the code and paste it below with the edited names in it, but if I click a different activity to go to maps, it brings me to the same marker as previously.
My Code for GoogleMapsActivity is below:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
// Add a marker at the Oval and move the camera
LatLng oval = new LatLng(53.3484013, -6.2605243);
mMap.addMarker(new MarkerOptions().position(oval).title("Oval Pub"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(oval));
/*
// Add a marker at Diceys and move the camera
LatLng diceys = new LatLng(53.3358088,-6.2636688);
mMap.addMarker(new MarkerOptions().position(diceys).title("Diceys Nightclub"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(diceys));
*/
}
public void changeType(View view)
{
if(mMap.getMapType() == GoogleMap.MAP_TYPE_NORMAL)
{
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
}
else
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}}
As you can see, I have commented out the code where I have tried adding a marker for a different location, but it seems to bring me to the same location as above.
Not sure if this is something simple or not as I am new to Google Maps in Android.
Any help would be greatly appreciated.
Thank you.
ArrayList<MarkerData> markerArray = new ArrayList<MarkerData>();
for(int i = 0 ; i < markersArray.size() ; i++ ) {
createMarker(markersArray.get(i).getLatitude(), markersArray.get(i).getLongitude(), markersArray.get(i).getTitle(), markersArray.get(i).getSnippet(), markersArray.get(i).getIconResID());
}
....
protected void createMarker(double lat, double lon, String title, String snippet, int iconResID) {
return googleMap.addMarker(new MarkerOptions()
.position(new LatLng(lat, lon))
.anchor(0.5f, 0.5f)
.title(title)
.snippet(snippet);
.icon(BitmapDescriptorFactory.fromResource(iconResID)));
}
Tying it all together:
ArrayList<LatLng> locations = new ArrayList();
locations.add(new LatLng(30.243442, -1.432320));
locations.add(new LatLng(... , ...));
.
.
.
for(LatLng location : locations){
mMap.addMarker(new MarkerOptions()
.position(location)
.title(...)
}
In First Location activity:
Intent i = new Intent(FirstLocationActivity.this, MapsActivity.class);
String keyLatitude = ""; //enter the value
String keyLongitude = ""; //enter the value
i.putExtra("latitude", keyLatitude );
i.putExtra("longitude", keyLongitude );
startActivity(i);
similarly do the same for activity two location, add its corresponding latitude and longitude in extra
In your mapsActivity,
String latitude="";
String longitude ="";
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.table);
Bundle bundle = getIntent().getExtras();
latitude = bundle.getString("latitude");
longitude = bundle.getString("longitude");
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
// Add a marker at the Oval and move the camera
LatLng oval = new LatLng(latitude,longitude);
mMap.addMarker(new MarkerOptions().position(oval).title("Oval Pub"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(oval));
}