I am displaying the location of buses in google map where I am getting the location from the bus database table on the server. I am facing problem to delete or to update their locations on google map since a new marker is always being created when the longitude and latitude change in the bus table. How can I delete and update specific Marker in Google Map?
I appreciate any help.
Code:
private void gotoLocation(double lat, double lng, String route_direct) {
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
final float zoom = 11;
LatLng ll = new LatLng(lat, lng);
if (lat != 0 && lng != 0 && !route_direct.isEmpty()) {
MarkerOptions markerOpt = new MarkerOptions().title(route_direct)
.position(ll).visible(true);
Marker marker = map.addMarker(markerOpt);
marker.showInfoWindow();
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, zoom);
map.moveCamera(update);
}
}
I solved in this way. I created HashMap for markers.
Sample,
HashMap<String, Marker> markerlist = new HashMap<>();
markerlist.put(route_direct, yourmarker);//add marker to list
markerlist.get(route_direct);//get marker from list
Then in your update process, try this code
if(markerlist.containsKey(route_direct)){
Marker marker = markerlist.get(route_direct);
//update marker
}else{
//add marker or do anything
}
but to use this flow, you need to have unique data for marker such as marker id.
Hope this will help you. Good luck.
Here we have used on our project in didTap marker delegates, We have created two functions one is Create marker and second one is delete marker code is given below in IOS swift
1.CreateMarker function call when you get Response from APIs
2.DeleteMarker call when you want to delete marker from map
//MARK: CreateMarker
func CreateMarker(TripLocation:[RECDATA])
{
//let path = GMSMutablePath()
for i in 0..<TripLocation.count
{
// Marker icon
var image = UIImage(named: "ic_greenMark")
// Get location coordinate
let locationTujuan = CLLocation(latitude: Double(TripLocation[i].facilityLatitude ?? 0.0) , longitude: Double(TripLocation[i].facilityLongitude ?? 0.0) )
image = UIImage(named: "ic_greenMark")
// create marker
let marker = GMSMarker()
marker.position = CLLocationCoordinate2DMake(locationTujuan.coordinate.latitude, locationTujuan.coordinate.longitude)
// marker.title = titleMarker
marker.icon = image
marker.map = MapView
let camera = GMSCameraPosition.camera(withLatitude:CLLocationDegrees(TripLocation[i].facilityLatitude!), longitude: CLLocationDegrees(TripLocation[i].facilityLongitude ?? 0.0), zoom: 8)
MapView.camera = camera
// append marker into markers array to show all marker in map
markers.append(marker)
}
}
//MARK: DeleteMarker
func DeleteMarker(marker:GMSMarker)
{
// Create Temp Object array
var Tempmarkers = [RECDATA]()
//check marker is exist or not
for obj in arrayRECDATA
{
let lat = Double(obj.facilityLatitude!)
let log = Double(obj.facilityLongitude!)
// remove marker from object array
if marker.position.latitude != lat && marker.position.longitude != log
{
Tempmarkers.append(obj)
}
}
// store temp array into original array
arrayRECDATA = Tempmarkers
// clean all marker and reload
MapView.clear()
CreateMarker(TripLocation: arrayRECDATA)
}
Thank you :)
Define variable for each marker like
Marker m1;
Marker m2;
etc.
And do whatever operation on specific marker using that variable. To delete the specific marker
m1.delete ();
m2.delete ();
Something like this, you can try and let me know if you face any issue.
Related
There is a Google map on my Android and I am new to the new Google Maps API. There is an initial marker on it.
This is the method to show the map and the initial marker:
#Override
public void onMapReady(GoogleMap map) {
//map is ready
// latitude and longitude
double latitude = latitud_del_hotel;
double longitude =longitud_del_hotel;
// create marker
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title(nombre_del_hotel).icon(BitmapDescriptorFactory.fromResource(R.drawable.poi));
// Changing marker icon
// marker.icon(BitmapDescriptorFactory
// .defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// adding marker
map.addMarker(marker);
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(latitud_del_hotel, longitud_del_hotel)).zoom(15).build();
map.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
Now, I need to put other markers on it. These markers are JSON objects that I am retrieving on another method from the activity.
May be my question is stupid, but I don't know how to add markers on the same map but created on another method.
This is how am I creating a new marker on another method:
hotel.setNombre(obj.getString("nombre_hotel"));
hotel.setLatitud(obj.getDouble("latitud_hotel"));
hotel.setLongitud(obj.getDouble("longitud_hotel"));
hotel.setDireccion(obj.getString("direccion_hotel"));
String nombre = obj.optString("nombre_hotel");
Log.d("NOMBRE=", nombre);
String latitud = obj.optString("latitud_hotel");
double latitud_del_hotel = Double.parseDouble(latitud);
String longitud = obj.optString("longitud_hotel");
double longitud_del_hotel = Double.parseDouble(longitud);
// create marker
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitud_del_hotel, longitud_del_hotel)).title(nombre).icon(BitmapDescriptorFactory.fromResource(R.drawable.poi));
map.addMarker(marker);
But obviously, the line map.addMarker(marker); shows a warning: Cannot resolve symbol map.
Sorry if it is easy to solve, but I cannot.
Thank you.
In your onMapReady(...) add a field reference to the returned map.
public void onMapReady(GoogleMap map) {
this.googleMap = map;
Then, you can do:
// create marker
if(this.googleMap != null) {
MarkerOptions marker = new MarkerOptions(...);
this.googleMap.addMarker(marker);
}
This might create what's known as a race condition - if your network call to retrieve hotel location information returns a result before the map is ready, you will never get the results added into the map.
You could combat this by doing:
// Create this as a field:
List<MarkerOptions> markerOptions = new ArrayList<>();
MarkerOptions marker = new MarkerOptions(...);
if(this.googleMap != null) {
this.googleMap.addMarker(marker);
} else {
this.markerOptions.add(marker);
}
Then, at the bottom of onMapReady(...):
if(this.markerOptions != null && !this.markerOptions.isEmpty()) {
for(MarkerOption markerOption : this.markerOptions) {
this.googleMap.addMarker(markerOption);
}
}
I have a checkboxlist where the user can select some routes then a reponse is being getting from the server. I have method gotoLocation to upadte the location of the markers as well to add a new marker in the map when a new one is being inserted into the table on the serverside with the same route.
I had problem with adding a new marker to the map before so when I inserted data for a new marker with the same selected route in my database table, the new inserted one was not added to the map. I stored the id and Marker in the HashMap before I solved this problem by storing the data of the marker as String in the HashMap in this case the new inserted data is being added to the map as marker.
Now in the Update block I need to convert this data latit,longit, rout_dirc to marker to remove the old one from the map and HashMap before updating its location. How can I do that in my case? How can I remove the old marker from the map since I dont have Marker in the HashMap now also I cant use marker.remove() to delete the old one?
I appreciate any help
Code:
public class Map extends FragmentActivity {
GoogleMap map;
static HashMap<Integer, String> markerMap = new HashMap<Integer, String>();
static String marker_string;
static Marker marker = null;
private void gotoLocation(int id, double lat, double lng,
String route_direct) {
final float zoom = 11;
LatLng ll = null;
if (markerMap.containsKey(id)) {
// Update the location.
marker_string = markerMap.get(id);
String[] marker_string_split = marker_string.split(",");
double latit = Double.parseDouble(marker_string_split[0]);
double longit = Double.parseDouble(marker_string_split[1]);
String rout_dirc = marker_string_split[2];
LatLng LL_2 = new LatLng(lat, lng);
MarkerOptions markerOpt2 = new MarkerOptions().title(route_direct)
.position(LL_2);
// This here doest work.
marker.remove();
// Remove from the HashMap tp add the new one.
markerMap.remove(id);
ll = new LatLng(lat, lng);
MarkerOptions markerOpt = new MarkerOptions().title(route_direct)
.position(ll);
marker = map.addMarker(markerOpt);
String lat1 = Double.toString(lat);
String lng1 = Double.toString(lng);
String data = lat1 + "," + lng1 + "," + route_direct;
markerMap.put(id, data);
zoom();
} else {
// Add a new marker
String lat1 = Double.toString(lat);
String lng1 = Double.toString(lng);
String data = lat1 + "," + lng1 + "," + route_direct;
markerMap.put(id, data);
ll = new LatLng(lat, lng);
MarkerOptions markerOpt = new MarkerOptions().title(route_direct)
.position(ll);
marker = map.addMarker(markerOpt);
zoom();
}
}
}
It seems like your marker in marker.remove(); is set to null and it won't do any good unless you have a reference of the markers you want to delete. If you want to remove all old markers, then you can try the following:
mMap = super.getMap();
map.clear();
This removes everything. Otherwise, when you add markers you should have a reference if you need to delete it later.
For example, your marker variable is:
Marker marker = map.addMarker(..);
Then you can remove it by marker.remove();
Hope this makes sense;
mapView.clear()
it will remove all markers in the map,
you can also refer the google official documentation
https://developers.google.com/maps/documentation/ios-sdk/marker
I have a map with 3 options. A search function, a nearby locations function, and a click on the map to set marker option. I want to save these locations in my Parse backend, but the only one I was able to figure out how to do is the set marker option.
When I do a nearby search and get a bunch of results I want to be able to click on one of the markers (see the title and location) and then click on the save button to save to my backend. Here's what I have:
#Override
protected void onPostExecute(List<HashMap<String,String>> list){
// Clears all the existing markers
mGoogleMap.clear();
for(int i=0;i<list.size();i++){
// Creating a marker
markerOptions = new MarkerOptions();
// Getting a place from the places list
HashMap<String, String> hmPlace = list.get(i);
// Getting latitude of the place
double lat = Double.parseDouble(hmPlace.get("lat"));
// Getting longitude of the place
double lng = Double.parseDouble(hmPlace.get("lng"));
// Getting name
final String name = hmPlace.get("place_name");
// Getting vicinity
final String vicinity = hmPlace.get("vicinity");
latLng = new LatLng(lat, lng);
// Setting the position for the marker
markerOptions.position(latLng);
// Setting the title for the marker.
//This will be displayed on taping the marker
markerOptions.title(name + " : " + vicinity);
// Placing a marker on the touched position
mGoogleMap.addMarker(markerOptions);
}
}
I have tried to add setOnMarkerClickListener, but it ends up not showing me anything (right now I at least get the title and location).
I know how to save the location to my backend but I'm not sure how to get the location of the clicked marker.
Just set the onMarkerClickListener for your map object, the callback returns to you the Marker object.
Marker has an attribute called Position which has the LatLng value that you require. Also you have to add a infoWindow, using the details the Marker object has to display name and other details.
#Override
public boolean onMarkerClick(Marker marker) {
LatLng markerLocation=marker.getPosition();
return false;
}
I'm developing an Android app which traces the path from current location to a specific destination. It works well. But there is an exception scenario.
When user clicks on a destination marker, it needs to move the map to another location with zoom. But only get zoomed without moving to the second location.
This is my relating code segment with that. If you can please help me with this. Thanks in advance.
double Kumana1_Latitude = 6.573022;
double Kumana1_Longitude = 81.666875;
double Kumana2_Latitude = 6.649353;
double Kumana2_Longitude = 81.770114;
final LatLng Kumana = new LatLng(Kumana1_Latitude, Kumana1_Longitude);
final LatLng Kumana2 = new LatLng(Kumana2_Latitude,Kumana2_Longitude);
Marker Kumana_marker = mGoogleMap.addMarker(new MarkerOptions()
.title("Kumana National Park")
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
.position(Kumana));
Kumana_marker.showInfoWindow();
mGoogleMap.setOnMarkerClickListener(new OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker m) {
//here it get Zoomed, but does not move to the new location
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(Kumana2, 13));
m.remove();
Toast.makeText(getApplicationContext(),
"Tap on the Kumana National Park entreance", Toast.LENGTH_LONG)
.show();
});
}
Put the marker in onLocationChanged() and plot the marker. First remove the marker and then add the new marker with the new location.
All this code must come under onLocationChanged()
Check first
(if marker == null){
//plot marker
}
else{
//remove first marker..
//add new marker
}
Try to call super.onMarkerClick(m) in your overriden function ònMarkekClick(Marker m)`.
So I'm storing markers from my map into a sqlite database. I am trying to query the markers by latitude and longitude. So for testing I am adding the marker to a specific location. When I check the markers position it gives me another location. What is causing this?
private void drawMarker(LatLng point, String title, String snippet){
// Creating an instance of MarkerOptions
MarkerOptions markerOptions = new MarkerOptions();
// Setting latitude and longitude for the marker
LatLng l = new LatLng(37.52100000000001, -77.44800000000001);
markerOptions.position(l);
markerOptions.title(title);
markerOptions.snippet(snippet);
// Adding marker on the Google Map
googleMap.addMarker(markerOptions);
}
This is the code to extract the marker position
googleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
marker1 = marker;
LatLng mlatlong = marker1.getPosition();
markerLat = Double.toString(mlatlong.latitude);
markerLng = Double.toString(mlatlong.longitude);
latitude = mlatlong.latitude;
longitude = mlatlong.longitude;
Log.i("Marker", mlatlong.latitude +","+mlatlong.longitude);
markerDialog();
}
});
This gives me the position
06-20 21:53:52.447: I/Marker(15221): 37.52100000569583,-77.44800008833408
In Java, and most other languages you'll come accross, double is not stored as a precise value.
You can read more here.
Also, it shouldn't really matter the locations you posted are extremely close to each other.