Consolidating Methods For Adding Marker To Map - android

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!

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.

Is it possible to add markers from an AsyncTask?

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);
}
}

Google Map does not moving to the new LatLng location

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

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.

Placing different marker icons for different users in android application on GoogleMaps

i want to add points on a the map in android application , i get the points (Latitude,Longitude) from web service and want to place them on the map with markers but the problem that i have two kinds of users so i want to place one of them with a marker different than the other users
you could do some thing like that:
for (Task tempTask : SGTasksListAppObj.getInstance().tasksRepository.getTasksRepository())
{
LatLng latlng = new LatLng(tempTask.getLatitude(),tempTask.getLongtitude());
if (tempTask.getStatus().contentEquals(TasksListActivity.STATUS_WAITING))
{
newmarker = map.addMarker(new MarkerOptions().position(latlng).title(tempTask.getTitle()).icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_for_map_blue)));
}
else if (tempTask.getStatus().contentEquals(TasksListActivity.STATUS_IN_PROGRESS))
{
newmarker = map.addMarker(new MarkerOptions().position(latlng).title(tempTask.getTitle()).icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_for_map_bordo)));
}
else if (tempTask.getStatus().contentEquals(TasksListActivity.STATUS_ON_THE_WAY))
{
newmarker = map.addMarker(new MarkerOptions().position(latlng).title(tempTask.getTitle()).icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_for_map_turkiz)));
}
else if (tempTask.getStatus().contentEquals(TasksListActivity.STATUS_COMPLETE))
{
newmarker = map.addMarker(new MarkerOptions().position(latlng).title(tempTask.getTitle()).icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_for_map_orange)));
}
else if (tempTask.getStatus().contentEquals(TasksListActivity.STATUS_FAILED))
{
newmarker = map.addMarker(new MarkerOptions().position(latlng).title(tempTask.getTitle()).icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_for_map_purpul)));
}
}
as you see I am setting a different icon with a different color for the marker depending on it's status.
you could do some thing similar, just change the check you preform.

Categories

Resources