I'm having some troubles with onMarkerClick
Basically for now I just want that when ANY marker previously created starts the same activity when clicked. I will implement the filtering of the marker later on.
What I get now is no error. Simply nothing happens when the marker is clicked.
Here is my source:
I'm looping through a database to populate the map and then the markers are displayed
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class NevianoMaps extends Activity implements OnMarkerClickListener{
private GoogleMap googleMap;
DatabaseHandler db = new DatabaseHandler(this);
double latitude;
double longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.neviano_maps);
try {
// Loading map
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* function to load map. If map is not created it will create it for you
* */
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
CameraPosition cameraPosition = new CameraPosition.Builder().target(
new LatLng(double value, double value)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
//Luoghi di interesse check
if (getIntent().getIntExtra("str1", 0) == 0){
for(int x = 1; x < 6; x = x+1) {
latitude = db.getCultura(x).getCoordLat();
longitude = db.getCultura(x).getCoordLong();
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude)).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.title(db.getCultura(x).getName()));
}
}
if (getIntent().getIntExtra("str1", 1) == 1){
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(double value, double value)).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
.title("Sport"));
}
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
#Override
public boolean onMarkerClick(Marker arg0) {
Intent i = new Intent(this, informazioni.class);
//i.putExtra("str1", db.getCulturaName(arg0.getTitle()).getDescription());
startActivity(i);
return false;
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
}
Hope somebody can help! Thank you
In your initilizeMap() method, please add this line after you've got your map:
googleMap.setOnMarkerClickListener(this);
Related
I have a MapsActivity Class, where it starts at a fixed point set on the map. I'm calling a Thread, where Map is only fully loaded, when the return is true. (I'll do a search on a DB through the Web Service where it will return me Lat and Long values to play on the map, and that value will be changed every 15 seconds).
I needed to know, how do I change the position of a Marker out of the class onMapReady.
Follows the MapsActivity class
package com.example.patrickcamargo.myapplication.Maps;
import android.app.ProgressDialog;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnSuccessListener;
public class MapsActivity extends SupportMapFragment implements GoogleMap.OnMyLocationButtonClickListener, OnMapReadyCallback,
ActivityCompat.OnRequestPermissionsResultCallback, GoogleMap.OnMapClickListener {
private GoogleMap mMap;
Marker marker;
LatLng latLng = new LatLng(-23.497444, -47.440722);
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
private FusedLocationProviderClient mFusedLocationClient;
public Double latitude, longitude;
public ProgressDialog getProgress() {
return progress;
}
public void setProgress(ProgressDialog progress) {
this.progress = progress;
}
private ProgressDialog progress;
boolean teste = true;
boolean teste2 = true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getMapAsync(this);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(getActivity());
mFusedLocationClient.getLastLocation().addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if(location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
Toast toast = Toast.makeText(getContext(),"LAT: " + location.getLatitude() + "LONG: " + location.getLongitude(),Toast.LENGTH_LONG);
toast.show();
}
}
});
//TESTE DE EVENTO
progress = new ProgressDialog(getContext());
progress.setMessage("AGUARDE ENQUANTO IDENTIFICAMOS O SERVIÇO...");
progress.show();
progress.setCanceledOnTouchOutside(false);
ThreadCarregarChamado threadCarregarChamado = new ThreadCarregarChamado();
threadCarregarChamado.setMapsActivity(this);
threadCarregarChamado.start();
//CRIADO UM LOOP INFINITO, PARA QUE SÓ SEJA CARREGADO O MAPA TOTALMENTE, QUANDO O RETORNO DO CHAMADO JÁ TIVER UM FUNCIONARIO DISPONIVEL
//E TAMBEM VINCULADO COM ESSE CHAMADO QUE FOI ABERTO
//ENQUANTO NÃO FOR VINCULADO UM FUNCIONARIO, NÃO IRA SER EXECUTADO DAQUI PRA FRENTE
while (teste);
//onMapReady(mMap);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
enableMyLocation();
mMap = googleMap;
mMap.setOnMapClickListener(this);
// Add a marker in Sydney and move the camera
marker = mMap.addMarker(new MarkerOptions()
.position(latLng)
.title("Testando")
.snippet("Population: 776733"));
}
private void enableMyLocation() {
if (ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
PermitirLocalizacao.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE,
android.Manifest.permission.ACCESS_FINE_LOCATION, true);
} else if (mMap != null) {
mMap.setMyLocationEnabled(true);//BOTÃO PARA MUDAR CAMERA PARA POSIÇÃO ATUAL}
LatLng latLng = new LatLng(latitude, longitude);
//mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); JOGA O ZOOM DIRETO NA POSIÇÃO ATUAL DO CLIENTE
//mMap.animateCamera(CameraUpdateFactory.zoomTo(80));
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) {
return;
}
if (PermitirLocalizacao.isPermissionGranted(permissions, grantResults,
android.Manifest.permission.ACCESS_FINE_LOCATION)) {
enableMyLocation();
} else {
//resume.mPermissionDenied = true;
}
}
#Override
public boolean onMyLocationButtonClick() {
return false;
}
#Override
public void onMapClick(LatLng latLng) {
Toast toast = Toast.makeText(getContext(),"Coordenadas: " + latLng.toString(),Toast.LENGTH_LONG);
toast.show();
}
public void MarcarGuincho()
{
teste=false;
marker.setPosition(new LatLng(-25.63356, -47.440722));
//latLng = (-23.497444, -47.440722);
}
}
Now my Thread
package com.example.patrickcamargo.myapplication.Maps;
import android.app.ProgressDialog;
import android.content.Context;
import com.example.patrickcamargo.myapplication.Conexao;
import com.example.patrickcamargo.myapplication.ConexaoInterface;
import org.json.JSONException;
public class ThreadCarregarChamado extends Thread implements ConexaoInterface{
private ProgressDialog progress;
private Context context;
Conexao conexao;
public MapsActivity getMapsActivity() {
return mapsActivity;
}
public void setMapsActivity(MapsActivity mapsActivity) {
this.mapsActivity = mapsActivity;
}
private MapsActivity mapsActivity;
#Override
public void run() {
//conexao = new Conexao(context, this, "ThreadCarregarChamado.java");
//conexao.execute("teste.php?","");
try {
depoisDownload("OK");
Thread.sleep(5000);
} catch (JSONException e) {
} catch (InterruptedException e) {
}
}
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
#Override
public void depoisDownload(String result) throws JSONException {
if(result.equals("FALSE\r"))
{
run();
}
else {
mapsActivity.MarcarGuincho();
ProgressDialog progress;
progress = mapsActivity.getProgress();
progress.dismiss();
mapsActivity.setProgress(progress);
}
}
}
In the MarcarGuincho class, this is where I need to change the position of the marker set above, but it is giving me as null for me, so this is giving error ...
Error in this line
marker.setPosition(new LatLng(-25.63356, -47.440722));
Logcat
10-02 13:29:43.628 29584-30901/com.example.patrickcamargo.myapplication E/AndroidRuntime: FATAL EXCEPTION: Thread-240709
Process: com.example.patrickcamargo.myapplication, PID: 29584
com.google.maps.api.android.lib6.common.apiexception.c: Not on the main thread
at com.google.maps.api.android.lib6.common.k.b(:com.google.android.gms.DynamiteModulesB#11517436:11)
at com.google.maps.api.android.lib6.common.p.a(:com.google.android.gms.DynamiteModulesB#11517436:5)
at com.google.maps.api.android.lib6.impl.cz.c(:com.google.android.gms.DynamiteModulesB#11517436:176)
at com.google.android.gms.maps.model.internal.q.onTransact(:com.google.android.gms.DynamiteModulesB#11517436:18)
at android.os.Binder.transact(Binder.java:387)
at com.google.android.gms.internal.zzed.zza(Unknown Source)
at com.google.android.gms.maps.model.internal.zzr.getPosition(Unknown Source)
at com.google.android.gms.maps.model.Marker.getPosition(Unknown Source)
at com.example.patrickcamargo.myapplication.Maps.MapsActivity.MarcarGuincho(MapsActivity.java:148)
at com.example.patrickcamargo.myapplication.Maps.ThreadCarregarChamado.depoisDownload(ThreadCarregarChamado.java:55)
at com.example.patrickcamargo.myapplication.Maps.ThreadCarregarChamado.run(ThreadCarregarChamado.java:30)
at com.example.patrickcamargo.myapplication.Maps.ThreadCarregarChamado.depoisDownload(ThreadCarregarChamado.java:60)
at com.example.patrickcamargo.myapplication.Maps.ThreadCarregarChamado.run(ThreadCarregarChamado.java:30)
at com.example.patrickcamargo.myapplication.Maps.ThreadCarregarChamado.depoisDownload(ThreadCarregarChamado.java:60)
at com.example.patrickcamargo.myapplication.Maps.ThreadCarregarChamado.run(ThreadCarregarChamado.java:30)
Line 148 = marker.remove();
Try using
teste = false;
LatLng latLng1 = new LatLng(-25.63356, -47.440722);
if(marker != null)
{
marker.remove();
marker = mMap.addMarker(new MarkerOptions()
.position(latLng1)
.title("Testando")
.snippet("Population: 776733"));
}
Instead of LocationManager, I have use LocationServices method to get current gps location and location updates.
this is the code:
public void onConnected(#Nullable Bundle bundle) {
mLocationRequest = new LocationRequest();//PRIORITY_BALANCED_POWER_ACCURACY
mLocationRequest.setInterval(1000*30*1);
mLocationRequest.setFastestInterval(1000*30*1);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest,this);
}
}
public void onLocationChanged(Location location) { mLastLocation = location;
if (mCurrLocationMarker != null)
{
mCurrLocationMarker.remove();
}
//Place current location marker
latLng = new LatLng(location.getLatitude(), location.getLongitude());
lat= location.getLatitude();
log=location.getLongitude();
trim_check_location_change(lat,log);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(""+s);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
CurrentLocation = latLng;
}
As I move from from one place to another, blue marker moves accordingly.
however onlocationchanged method never gets called.
I've developed fused location api demo application and utility pack here.
General Utilities
Try it if useful for you. To get location using fused location api, you just have to write following snippet...
new LocationHandler(this)
.setLocationListener(new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// Get the best known location
}
}).start();
And if you want to customise it, simply find documentation here...
https://github.com/abhishek-tm/general-utilities-android/wiki/Location-Handler
Update
I've written a sample code according to your need, try this one...
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import in.teramatrix.utilities.service.LocationHandler;
import in.teramatrix.utilities.util.MapUtils;
/**
* Lets see how to use utilities module by implementing location listener.
*
* #author Khan
*/
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap map;
private Marker marker;
private LocationHandler locationHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Obtaining an instance of map
FragmentManager manager = getSupportFragmentManager();
SupportMapFragment mapFragment = (SupportMapFragment) manager.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
this.locationHandler = new LocationHandler(this)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(5000)
.setFastestInterval(10000)
.setLocationListener(this);
}
#Override
public void onMapReady(GoogleMap map) {
this.map = map;
this.locationHandler.start();
}
#Override
public void onLocationChanged(Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
if (marker == null) {
marker = MapUtils.addMarker(map, latLng, R.drawable.ic_current_location);
map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14), 500, null);
} else {
marker.setPosition(latLng);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (locationHandler != null) {
locationHandler.stop();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == LocationHandler.REQUEST_LOCATION) {
locationHandler.start();
}
}
}
Hope it will help you.
Basically I am working on Google Map in which I have Google Map Activity and user click on any place of Google Map I was adding marker on this click and I have one button on this button click I take this marker position and put it to my Firebase Database.My complete code was working, but the problem is that when I click on the button which takes marker latlang to Firebase, my latlang value successfully update and my map Activity is re-transited (e.g./i.e. like Intent from current Activity to self Activity) that for my map was reloaded and I lose marker on screen.
Here is my Java code:
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.firebase.client.Firebase;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class PickUpActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, View.OnClickListener, GoogleMap.OnMapClickListener {
private static final int PERMISSION_REQUEST_CODE = 1;
public double marker_latitude;
public double marker_longitude;
private GoogleMap mMap;
private GoogleApiClient googleApiClient;
private Marker marker;
private double latitude;
private double longitude;
private Button btn;
private Bus bus;
private Firebase ref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pick_up);
Firebase.setAndroidContext(this);
btn = (Button) findViewById(R.id.btn_pick);
ref = new Firebase(Config.FIREBASE_URL);
bus = new Bus();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mMap = mapFragment.getMap();
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.build();
btn.setOnClickListener(this);
mMap.setOnMapClickListener(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
#Override
public void onConnected(#Nullable Bundle bundle) {
getCurrentLocation();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
protected void onStart() {
googleApiClient.connect();
super.onStart();
}
#Override
protected void onStop() {
googleApiClient.disconnect();
super.onStop();
}
private void getCurrentLocation() {
if (!checkPermission()) {
requestPermission();
}
Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (location != null) {
longitude = location.getLongitude();
latitude = location.getLatitude();
moveMap();
}
}
private void moveMap() {
LatLng latLng = new LatLng(latitude, longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
private boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(PickUpActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(PickUpActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION)) {
Toast.makeText(PickUpActivity.this, "GPS permission allows us to access location data. Please allow in App Settings for additional functionality.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(PickUpActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getCurrentLocation();
} else {
}
break;
}
}
#Override
public void onClick(View v) {
if (v == btn) {
if (marker == null) {
Toast.makeText(PickUpActivity.this, "Please Select Any Place", Toast.LENGTH_SHORT).show();
} else {
bus.setlatitude(marker_latitude);
bus.setlongitude(marker_longitude);
ref.child("school1").child("bus1").child("parents").child("parent01").child("pickuppoint").setValue(bus);
Toast.makeText(PickUpActivity.this, "Pick Up Point Set", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onMapClick(LatLng latLng) {
mMap.clear();
marker = mMap.addMarker(new MarkerOptions()
.position(latLng) //setting position
.draggable(true) //Making the marker draggable
.title("" + latLng));
marker_latitude = latLng.latitude;
marker_longitude = latLng.longitude;
}
}
During analysis I found problem in below code:
bus.setlatitude(marker_latitude);
bus.setlongitude(marker_longitude);
ref.child("school1").child("bus1").child("parents").child("parent01").child("pickuppoint").setValue(bus);
If I put some static value on bus.setlatitude() and bus.setlongitude no re-transition occur. I don't know what I am doing wrong and what is solution for this problem.
if your user click on your Map the map will be cleared: mMap.clear();
#Override
public void onMapClick(LatLng latLng) {
mMap.addMarker(new MarkerOptions()
.position(latLng) //setting position
.draggable(true) //Making the marker draggable
.title(""+latLng));
marker_latitude = latLng.latitude;
marker_longitude= latLng.longitude;
}
Im developing an app using Google Maps v2 for Android and I managed to put a custom icon to the user's position but I can't remove the default one, so it overlays my custom icon like in the image:
(It is that big just for now :p )
My code is like:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
map.setMyLocationEnabled(true);
map.setOnMyLocationChangeListener(new OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
if (location == null)
return;
mPositionMarker = map.addMarker(new MarkerOptions()
.flat(true)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.logop1))
.anchor(0.5f, 1f)
.position(new LatLng(location.getLatitude(), location.getLongitude())));
}
});
}
So:
1) Is there a way to remove the default blue dot of user's current location?
2) Will the user location be updated when I move in the "real world" (I cant test it for conectivity reasons) or do I have to write/override a method to update users position?
Thanks in advance
You will have to stop using GoogleMap.setMyLocationEnabled and write a bit more code, including having your own LocationClient and adding Circle for accuracy.
You have to do that on your own.
- set to false gmaps.getUiSettings().setMyLocationButtonEnabled(false);
create your own location button
if you get your current location, set a marker with your icon on that
if you click on your location button, move the camera and center it to the map
That will remove the blue dot
map.setMyLocationEnabled(true); remove line
Thanks joao2fast4u (lol) and ṁᾶƔƏň ツ. I followed your recomendations and I managed to make it work. Since I didn't see any answer concrete to this problem I'm posting my solution here:
package com.onsoftwares.ufvquest;
import android.location.Location;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapActivity extends ActionBarActivity implements LocationListener, GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener {
private GoogleMap map;
private Marker mPositionMarker;
private LocationClient mLocationClient;
private LocationRequest mLocationRequest;
private LatLng mLatLng;
private boolean mUpdatesRequested = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
mLocationClient = new LocationClient(this, this, this);
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the interval ceiling to one minute
mLocationRequest.setFastestInterval(1000);
// Note that location updates are off until the user turns them on
mUpdatesRequested = false;
}
#Override
protected void onStart() {
super.onStart();
mLocationClient.connect();
};
#Override
protected void onStop() {
if (mLocationClient.isConnected()) {
mLocationClient.removeLocationUpdates(this);
mLocationClient.disconnect();
}
super.onStop();
};
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle arg0) {
mLocationClient.requestLocationUpdates(mLocationRequest, this);
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// Get the current location
Location currentLocation = mLocationClient.getLastLocation();
// Display the current location in the UI
if (currentLocation != null) {
LatLng currentLatLng = new LatLng (currentLocation.getLatitude(), currentLocation.getLongitude());
if (mPositionMarker == null) {
mPositionMarker = map.addMarker(new MarkerOptions()
.position(currentLatLng)
.title("Eu")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.male_user_marker)));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLatLng, 15));
} else
mPositionMarker.setPosition(currentLatLng);
}
}
}
I found a solution . The map may not have been initialized yet, try getMap() in a later point of the lifecycle, like onResume()
My code is
protected void onResume() {
super.onResume();
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
if (resultCode == ConnectionResult.SUCCESS){
Toast.makeText(getApplicationContext(),
"isGooglePlayServicesAvailable SUCCESS",
Toast.LENGTH_LONG).show();
if(gMap == null){
gMap = mMapView.getMap();
if(gMap != null){
gMap.setMyLocationEnabled(true);
gMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
}else{
Toast.makeText(getApplicationContext(),
"cannot getMap!",
Toast.LENGTH_LONG).show();
}
}
}else{
GooglePlayServicesUtil.getErrorDialog(resultCode, this, RQS_GooglePlayServices);
}
}
Edited you have done below step:
Add Play Services Library in project :
Eclipse > import > Android > Existing Android code in to workspace
Browse you SDK path like ~/android-sdk-linux/extras/google/google_play_services
import that project in to workspace
add above library project in to your project. run in Android Device only not in Emulator
it is simple check below code:
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends Activity {
private GoogleMap MAP;
#Override
protected void onCreate(Bundle arg0) {
// TODO Auto-generated method stub
//setTheme(R.style.Theme_Sherlock);
super.onCreate(arg0);
setContentView(R.layout.activity_main);
FragmentManager myFM = getSupportFragmentManager();
SupportMapFragment myMAPF = (SupportMapFragment) myFM
.findFragmentById(R.id.fragment1);
MAP = myMAPF.getMap();
MAP.setMyLocationEnabled(true);
MAP.setMapType(GoogleMap.MAP_TYPE_HYBRID);
MAP.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
// TODO Auto-generated method stub
MAP.addMarker(new MarkerOptions().position(point).title(
point.toString()));
}
});
}
}
more detail check this : clickhere & clickhere
as per your code check this:
Marker marker = map.add(new MarkerOptions()
.position(new LatLng(37.7750, 122.4183))
.title("San Francisco")
.snippet("Population: 776733"));
gMap.addMarker(marker);
Try this to add custom marker:
public void placingCurrentMarkerWithBalloon(String address)
{
LatLng current_latlng = new LatLng(cur_lat, cur_lng);
gMapview.addMarker(new MarkerOptions().position(current_latlng)
.title("Address")
.snippet(address)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.person_marker))
/*.icon(BitmapDescriptorFactory.defaultMarker())*/
).showInfoWindow();
}