Is it possible to add markers from an AsyncTask? - android

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

Related

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.

How to show received latitude/longitude from server on google map?

How to show latitude and longitude which I received from server on android map. I implemented google map V2 but don't know how to show gps coordinates on map. I came here after a lot of research and wasn't able to find a single reasonable solution for it. Can anyone please help me out?
So far my code of latitude and longitude values which I am reviving from server.
String lat, lon;
double l1,l2;
DB db = new DB(getApplicationContext());
HashMap<String,String> gps = new HashMap<String, String>();
gps = db.getGps();
lat = user.get("lati");
lon = user.get("longi");
Okay when I try to add marker on map according to latitude and longitude from server my app got force close and gives NullPointerException.
free.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String lat, lon;
double l1,l2;
DB db = new DB(getApplicationContext());
HashMap<String,String> gps = new HashMap<String, String>();
gps = db.getGps();
lat = user.get("lati");
lon = user.get("longi");
l1 = Double.parseDouble(lat);
l2 = Double.parseDouble(lon);
map.addMarker(new MarkerOptions().position(new LatLng(l1, l2))
.title("My Map Title"));
Your "map" variable may not be initialized. I add a marker like this:
SupportMapFragment smf = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mMap = smf.getMap();
if ( mMap != null ) {
LatLng newLatLong = new LatLng(dblLat, dblLong);
mMap.addMarker(new MarkerOptions().position(newLatLong)
.title(name)
.snippet(fullStrAddr));
}
Add a marker like this
Marker mymarker= map.addMarker(new MarkerOptions().position(new LatLng(lat, lon))
.title("My Map Title"));
This will set a marker at the latitude and longitude which was sent from the server..
Try it..

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!

Unable to see multiple marker on google Map

I want to show multiple markers on a google map. My latlng coordinates are fetched from a Parse database but I am not able see marker.
My second problem is that I want to show a title that is Restaurant Name with marker, how can I do this?
This is my code:
private class putMarker extends AsyncTask> {
#Override
protected ArrayList doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
Toast.makeText(getApplicationContext(),
longitude + " " + latitude, Toast.LENGTH_SHORT).show();
ParseQuery query = new ParseQuery(
"Details");
ParseGeoPoint myGeoPiont = new ParseGeoPoint(latitude,
longitude);
query.whereNear("location", myGeoPiont);
query.setLimit(10);
ob = query.find();
for (ParseObject resObj : ob) {
ParseGeoPoint location = resObj
.getParseGeoPoint("location");
restaurantName = (String) resObj.get("RestaurantName");
LatLng resLatLng = new LatLng(location.getLatitude(),
location.getLongitude());
Toast.makeText(getApplicationContext(),
restaurantName, Toast.LENGTH_SHORT)
.show();
PiontList.add(resLatLng);
}
} catch (Exception e) {
// TODO: handle exception
}
return PiontList;
}
protected void onPostExecute(ArrayList latlngList) {
for(LatLng res: latlngList)
{
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(res);
markerOptions.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
googleMap.addMarker(markerOptions);
}
}
}
Please help me out.
it might due to unreachability of googleMap object in onPostExecute() .
Please ensure that googleMap is declared globally.
if possible please paste whole code for better evaluation
Try this
// Create lat long points
Latlng[] point_new = new LatLng[8];
point_new[0] = new LatLng(31.5301843, 74.3207487);
point_new[1] = new LatLng(31.5214693,74.3236027);
point_new[2] = new LatLng(31.5194393, 74.3257327);
point_new[3] = new LatLng(31.4942166, 74.3004533);
point_new[4] = new LatLng(31.4864646, 74.2911203);
point_new[5] = new LatLng(31.4803596, 74.2787933);
point_new[6] = new LatLng(31.4764716, 74.2638203);
point_new[7] = new LatLng(31.4775236, 74.2628873);
// Add markers
for (int i = 0; i < point_new.length; i++) {
MarkerOptions markerOptions = new MarkerOptions()
.position(point_new[i]);
marker = mMap.addMarker(markerOptions);
marker.setTitle("Points");
marker.setSnippet("Distance = 9.6 km, Time = 20 minute/s");
marker.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.p));
}
// Set camera to last point with Zoom level 9
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(point_new[7], 9));
I see a few problems here.
As #Raghunandan mentioned, you cannot update the UI from doInBackground() so you cannot add markers from there. You can however, make your MarkerOptions objects here, and then attach them to the GoogleMap in your postExecute/or in the Activity that hosts the Google Maps.
In your onPostExecute(), you have not set any Title, or Snippet to your markers. Whenever you are creating your marker, make sure to set your title. Then when the user clicks on the marker, the default behavior shows your rest name as a title.
Code will be something like this(as also mentioned by #Inzimam Tariq IT :
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(res)
.setTitle(restaurantName)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
googleMap.addMarker(markerOptions);

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