Google Map does not moving to the new LatLng location - android

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)`.

Related

InfoWindows doesn't take each info window marker

I load the markers from sqlite and I do looping to get data from sqlite the put the marker to each latitude and longitude. It works.
But when I try to get the info window from each marker, it doesnt works. It just take one infowindow.
this is my code:
while (cursor.moveToNext()){
// mengambil koordinat lokasi ATM
title = cursor.getString(1).toString();
__global_endposition = cursor.getString(2).toString();
alamat = cursor.getString(3).toString();
String[] exp_endCoordinate = __global_endposition.split(",");
double lat_endposition = Double.parseDouble(exp_endCoordinate[0]);
double lng_endposition = Double.parseDouble(exp_endCoordinate[1]);
LatLng endx = new LatLng(lat_endposition, lng_endposition);
MarkerOptions options = new MarkerOptions()
.position(endx)
.title(title)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
// mMap.addMarker(options);
Marker marker = googleMap.addMarker(options);
mapBuilder.include(marker.getPosition());
addedMarker = true;
googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
Toast.makeText(getActivity(), alamat, Toast.LENGTH_SHORT).show();
}
});
}
This is my sqlite record:
enter image description here
When I clik to each marker, it only showed "Giant Ekspres, Jl. Urip Sumoharjo, Klitren, Gondokusuman, Kota Yogyakarta" to each marker info windows.
There is only one onInfoWindowClick listener per map object. In your case, you Toast the contents of alamat which will always be the last cursor result (column index 3) string.
If you want to display for each marker the alamat contents as it appears you intended then the simplest approach is to set the marker's tag field to the contents of alamat and then in the listener use the marker's tag field in the toast:
alamat = cursor.getString(3).toString();
// ...
MarkerOptions options = new MarkerOptions()
.position(endx)
.title(title)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
Marker marker = googleMap.addMarker(options);
marker.setTag(new String(alamat));
// ...
googleMap.setOnInfoWindowClickListener(new
GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
Toast.makeText(getActivity(), marker.getTag().toString(), Toast.LENGTH_SHORT).show();
}
});
You will soon find you may want to do more than just display the tag string. So you can either use a more complex object in the tag or use the marker id in the onInfoWindowClick to access a managed collection of marker data, like a Hashmap.

Google Place - set On Info Window Click Listener

How I can setOnInfoWindowClickListener if have this loop?
I'm trying to create an Android application. To retrieve data from json file I use retrofit.
I need help when clicking on the info window I want to show more information about the clicked place.
I want to display Toast with the name of clicked the Nearby Places.
for (int i = 0; i < response.body().getResults().size(); i++) {
Double lat = response.body().getResults().get(i).getGeometry().getLocation().getLat();
Double lng = response.body().getResults().get(i).getGeometry().getLocation().getLng();
final String placeName = response.body().getResults().get(i).getName();
// String vicinity = response.body().getResults().get(i).getVicinity();
// Double ratting = response.body().getResults().get(i).getRating();
final List <String> nameLocation = new ArrayList<>();
nameLocation.add(placeName);
MarkerOptions markerOptions = new MarkerOptions();
LatLng latLng = new LatLng(lat, lng);
// Position of Marker on Map
markerOptions.position(latLng);
// Adding Title to the Marker
markerOptions.title(placeName);
// Adding colour to the marker
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(markerColor));
// Adding Marker to the Camera.
Marker mMarker = mMap.addMarker(markerOptions);
// move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(12));
}
As you mentioned in the comments, you can show a toast in when a marker on your map is clicked by doing the following.
First attach a marker click listener to your map:
mMap.setOnMarkerClickListener(new OnMarkerClickListener {
public boolean onMarkerClick(final Marker marker) {
//TODO: Show your toast
}
});
Next within the click handler, create a new toast. Make sure you have the application context within this handler, so that you can attach the toast to that context.
final Context context = this;
mMap.setOnMarkerClickListener(new OnMarkerClickListener {
public boolean onMarkerClick(final Marker marker) {
Toast toast = Toast.makeText(context, marker.getTitle(), "Additional info", Toast.LENGTH_SHORT);
toast.show();
}
});

Update and delete specific marker in Google Map

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.

Consolidating Methods For Adding Marker To Map

In my app I am using an if/else statement that, onMapLongClick, will update the location of the marker, if one exists, or create a marker if one does not exist. I wanted to use SearchView with Google Places API, so I utilized a tutorial I found reading through posts on Stack Overflow. It utilizes search results from Google Places API to create a marker. Nice! However, it is using its own addMarker. So, I am hoping someone would be so kind as to get me going in the right direction so that I am able to tie the results being generated from Google Places API in with my method for adding a marker. (Teach the man to fish, not give the man a fish.)
My method:
#Override
public void onMapLongClick(LatLng point) {
if(marker != null){ //if marker exists (not null or whatever)
marker.setPosition(point);
}
else{
marker = map.addMarker(new MarkerOptions()
.position(point)
.title("Your Destination")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher))
.draggable(true));
}
if(marker!=null){
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(point)
.zoom(10)
.build();
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
Tutorial method for Google-Places-API results:
private void showLocations(Cursor c){
MarkerOptions markerOptions = null;
LatLng position = null;
map.clear();
while(c.moveToNext()){
markerOptions = new MarkerOptions();
position = new LatLng(Double.parseDouble(c.getString(1)),Double.parseDouble(c.getString(2)));
markerOptions.position(position);
markerOptions.title(c.getString(0));
map.addMarker(markerOptions);
}
if(position!=null){
CameraUpdate cameraPosition = CameraUpdateFactory.newLatLng(position);
map.animateCamera(cameraPosition);
}
}
There might be a better way to do it, but after tinkering with it a bit, I was able to recycle the code for my method into the tutorial method, and it looks like this:
private void showLocations(Cursor c){
LatLng position = null;
while(c.moveToNext()){
position = new LatLng(Double.parseDouble(c.getString(1)),Double.parseDouble(c.getString(2)));
if(marker != null){ //if marker exists (not null)
marker.setPosition(position);
}
else{
marker = map.addMarker(new MarkerOptions()
.position(position)
.title("Your Destination")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher))
.draggable(true));
}
if(position!=null){
CameraUpdate cameraPosition = CameraUpdateFactory.newLatLng(position);
map.animateCamera(cameraPosition);
}
}
}
Now, not matter whether the user long clicks on a location on the map, or selects one from given search results, there will only ever appear one user-set marker on the map. Wahoo!

Map marker doesn't point to exact location

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.

Categories

Resources