hi i have to implement Google map v2 in my application an it's perfect working. but my problem i have to send one Marker position from one activity to another activity and then add marker into Google map but i don't know it's not.
Post my code below.
public class BasicMapActivity extends FragmentActivity{
private GoogleMap mMap;
AlertMessages messages;
String latitude;
double lat = 0, lng = 0;
String longitude ;
String title = "", city = "";
static boolean is_back_pressed = false;
ImageView img;
GPSTracker gps;
RelativeLayout rel;
Marker Contactloc;
LatLng contactLoc;
Button ib_back;
static boolean is_window_pressed = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basic_demo_new);
img = (ImageView) findViewById(R.id.popup_h);
img.setVisibility(View.INVISIBLE);
gps = new GPSTracker(getParent());
messages = new AlertMessages(getParent());
Bundle b = getIntent().getExtras();
title = b.getString("title");
city = b.getString("City");
latitude = b.getString("latitude");
longitude = b.getString("longitude");
back_layout=(LinearLayout)findViewById(R.id.back_lay);
ib_back=(Button)findViewById(R.id.ib_back_music);
System.out.println("Lat:::" + latitude);
System.out.println("Long:::" + longitude);
setUpMapIfNeeded();
ib_back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
is_back_pressed = true;
TabGroupActivity parentActivity = (TabGroupActivity) getParent();
parentActivity.onBackPressed();
}
});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
try{
System.out.println("Map Pause state");
if(mMap!=null){
mMap.clear();
mMap=null;
TabGroupActivity parentActivity = (TabGroupActivity) getParent();
parentActivity.onBackPressed();
}
}catch(Exception e){
e.printStackTrace();
}
}
#Override
protected void onResume() {
super.onResume();
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getParent());
if (status == ConnectionResult.SUCCESS) {
setUpMapIfNeeded();
mMap.setMyLocationEnabled(true);
} else {
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, getParent(),
requestCode);
dialog.show();
}
}
protected LocationManager locationManager;
LatLng pos=null;
private void setUpMapIfNeeded() {
System.out.println("Setup If Needed");
// Do a null check to confirm that we have not already instantiated the
// map.
if (mMap == null) {
mMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map1)).getMap();
mMap.setMyLocationEnabled(true);
boolean isInternetPresent = isConnectingToInternet();
if (!isInternetPresent) {
// Internet Connection is not present
Toast.makeText(getParent(), "Internet Connection Error!",Toast.LENGTH_SHORT).show();
//messages.showAlertDialog(getParent(),
// "Internet Connection Error",
//"Please connect to working Internet connection");
// stop executing code by return
// return;
} else {
locationManager = (LocationManager) getParent()
.getSystemService(LOCATION_SERVICE);
// getting GPS status
if (!locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
showSettingsAlert();
}
if (gps.canGetLocation()) {
lat = gps.getLatitude();
lng = gps.getLongitude();
pos = new LatLng(lat, lng);
if (lat == 0.0 && lng == 0.0) {
Toast.makeText(getParent(), "Can't find location",
Toast.LENGTH_SHORT).show();
} else {
mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.mark_blue))
.position(pos)
.title("Current Location"));
double trans = 0.3;
for (int k = 100; k <= 500;) {
// draw circle
int radiusM = k;
int d = k; // diameter
Bitmap bm = Bitmap.createBitmap(d, d,
Config.ARGB_8888);
Canvas c = new Canvas(bm);
Paint p = new Paint();
p.setColor(getResources().getColor(
android.R.color.darker_gray));
c.drawCircle(d / 2, d / 2, d / 2, p);
// generate BitmapDescriptor from circle
// Bitmap
BitmapDescriptor bmD = BitmapDescriptorFactory
.fromBitmap(bm);
// mapView is the GoogleMap
mMap.addGroundOverlay(new GroundOverlayOptions()
.image(bmD)
.position(pos, radiusM * 2,
radiusM * 2)
.transparency((float) trans));
k = k + 100;
trans = trans + 0.1;
}
}
} else {
Toast.makeText(getParent(), "Can't find location",
Toast.LENGTH_SHORT).show();
}
}
mMap.getUiSettings().setCompassEnabled(true);
mMap.setTrafficEnabled(true);
mMap.getUiSettings().setTiltGesturesEnabled(true);
mMap.getUiSettings().setRotateGesturesEnabled(true);
mMap.getUiSettings().setScrollGesturesEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setZoomGesturesEnabled(true);
setUpMap();
} // Check if we were successful in obtaining the map.
if (mMap != null) {
mMap.setMyLocationEnabled(true);
setUpMap();
}
}
private void setUpMap() {
System.out.println("Setup Map");
try{
contactLoc=new LatLng(latitude, longitude);
Contactloc=mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.mark_red))
.position(new LatLng(latitude, longitude)).title(title)
.snippet(city));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
latitude, longitude), 18.0f));
}catch(Exception ew){
ew.printStackTrace();
}
}
}
please some one help me!
Add Marker like below
Contactloc=mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.mark_red))
.position(new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude)).title(title)
.snippet(city));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
latitude, longitude), 18.0f));
You need to Convert your latitude and longitude String values into Double. and AFAIK you said no not any error. your app defiantly crash over here with some logcat.
Related
This question already has answers here:
How can I show current location on a Google Map on Android Marshmallow?
(3 answers)
Closed 5 years ago.
My code create a route between two points on the map in the coordinates I'm trying to get past the coodernada from my current location to the fromPosition, using the low code. But he is giving 0,0 in Log.i;
double lat;
double lng;
LatLng fromPosition = new LatLng(lat, lng);
LatLng toPosition = new LatLng(-5.082434, -42.807364);
But I need the co-penned fromPosition to be my current position.
Thank you for any help.
public class MapsActivity2 extends FragmentActivity {
private GoogleMap map;
double lat;
double lng;
LatLng fromPosition = new LatLng(lat, lng);
LatLng toPosition = new LatLng(-5.082434, -42.807364);
ArrayList<LatLng> directionPoint;
Marker mPositionMarker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps2);
initializeMap();
Log.i("david", "LATLNG= " + fromPosition);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
long tempo = 1000; //5 minutos
float distancia = 1; // 30 metros
map.setMyLocationEnabled(true);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER , tempo , distancia, new LocationListener() {
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
#Override
public void onProviderEnabled(String arg0) {
Toast.makeText(getApplicationContext(), "GPS Habilitado", Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String arg0) {
Toast.makeText(getApplicationContext(), "GPS Desabilitado", Toast.LENGTH_LONG).show();
}
#Override
public void onLocationChanged(Location location) {
if (location == null)
return;
map.setMyLocationEnabled(true);
lat = location.getLatitude();
lng = location.getLongitude();
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new
LatLng(lat, lng), 16));
if (mPositionMarker == null) {
mPositionMarker = map.addMarker(new MarkerOptions()
.flat(true)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.car))
.anchor(0.5f, 0.5f)
.position(
new LatLng(location.getLatitude(), location
.getLongitude())));
}
animateMarker(mPositionMarker, location); // Helper method for smooth
// animation
map.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude())));
}
public void animateMarker(final Marker marker, final Location location) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final LatLng startLatLng = marker.getPosition();
final double startRotation = marker.getRotation();
final long duration = 500;
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
#Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float) elapsed
/ duration);
double lng = t * location.getLongitude() + (1 - t)
* startLatLng.longitude;
double lat = t * location.getLatitude() + (1 - t)
* startLatLng.latitude;
float rotation = (float) (t * location.getBearing() + (1 - t)
* startRotation);
marker.setPosition(new LatLng(lat, lng));
marker.setRotation(rotation);
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
}
}
});
}
}, null);
}
private void initializeMap() {
if (map == null) {
map = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
new WebserviceTask(this).execute();
}
}
public void setDirectionPoints(ArrayList<LatLng> result) {
directionPoint = new ArrayList<LatLng>();
directionPoint = result;
}
protected void onResume() {
super.onResume();
initializeMap();
}
public class WebserviceTask extends
AsyncTask<Void, Void, ArrayList<LatLng>> {
MapsActivity2 mContext;
PolylineOptions rectline;
public WebserviceTask(MapsActivity2 context) {
this.mContext = context;
}
#Override
protected void onPostExecute(ArrayList<LatLng> result) {
super.onPostExecute(result);
if (result != null) {
rectline = new PolylineOptions().width(10).color(Color.BLUE);
for (int i = 0; i < result.size(); i++)
rectline.add(result.get(i));
map.addPolyline(rectline);
}
}
#Override
protected ArrayList<LatLng> doInBackground(Void... params) {
GMapV2Direction md = new GMapV2Direction();
Document doc = md.getDocument(fromPosition, toPosition,
GMapV2Direction.MODE_DRIVING);
if (doc != null) {
ArrayList<LatLng> directionPoint = md.getDirection(doc);
rectline = new PolylineOptions().width(10).color(Color.RED);
for (int i = 0; i < directionPoint.size(); i++)
rectline.add(directionPoint.get(i));
return directionPoint;
} else
return null;
}
}
}
/**Implement the code Snipet in your initializeMap() Method***/
private void initializeMap()
{
if (map == null)
{
map = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
new WebserviceTask(this).execute();
map.moveCamera(CameraUpdateFactory.newLatLngZoom(fromPosition, 10));
map.addMarker(new MarkerOptions()
.title("Marker Location")
.snippet("Marker Location Address")
.position(fromPosition));
map.getUiSettings().setMapToolbarEnabled(true);
}
}
map with default marker that is never set
In the middle of the map there is a marker, which is always shown on this location when I start the activity with the map fragment in it. But I never set this marker... Does someone know why this is and maybe how I can delete this marker?
Here is my code:
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
int permissionCheck = ContextCompat.checkSelfPermission(MapsActivity.this,
android.Manifest.permission.ACCESS_FINE_LOCATION);
if(permissionCheck == PackageManager.PERMISSION_GRANTED){
getCurrentLocation();
onSearch();
}else if(permissionCheck == PackageManager.PERMISSION_DENIED){
onSearch();
}
}
//gets current location of the user.
public void getCurrentLocation() {
double lat = 0;
double lng = 0;
try {
mMap.setMyLocationEnabled(true); //allows query of current location.
}catch(SecurityException e){
e.printStackTrace();
}
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Geocoder geocoderGetAddress = new Geocoder(MapsActivity.this);
try{
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location!=null) {
lat = location.getLatitude();
lng = location.getLongitude();
}
}catch(SecurityException e){
e.printStackTrace();
}
//the rest of this method gets the address from the geocoder, so that it can be displayed as a String on the marker info window.
String displayAddress ="";
try {
List<Address> currAddress = geocoderGetAddress.getFromLocation(lat, lng, 1);
if(currAddress.size() >0){
for(int i=0; i<currAddress.get(0).getMaxAddressLineIndex();i++){
displayAddress += currAddress.get(0).getAddressLine(i) +"\n";
}
}
}catch (IOException e){
e.printStackTrace();
}
mMap.addMarker(new MarkerOptions().position(new LatLng(lat,lng)).title(myLoc).snippet(displayAddress));
LatLng myLatLng = new LatLng(lat, lng);
mMap.animateCamera(CameraUpdateFactory.newLatLng(myLatLng));
initAcceptButton();
}
Thanks!
I just solved the problem with adding
if(lat!= 0 || lng != 0){
//add marker here
}
on MapActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//show error dialog if GooglePlayServices not available
if (!isGooglePlayServicesAvailable()) {
finish();
}
setContentView(R.layout.activity_add_map);
ButterKnife.inject(this);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading ...");
progressDialog.show();
turnGPSOn();
setUpMapIfNeeded();
}
#Override
public void onLocationChanged(Location location) {
// TextView locationTv = (TextView) findViewById(R.id.latlongLocation);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions()
.position(latLng)
.title("Start Point")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_marker))
);
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15.5f), 4000, null);
progressDialog.dismiss();
latAwal = location.getLatitude();
lngAwal = location.getLongitude();
}
private void turnGPSOn(){
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(!provider.contains("gps")){ //if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
}
public void setUpMapIfNeeded(){
if (googleMap == null){
SupportMapFragment supportMapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap);
googleMap = supportMapFragment.getMap();
googleMap.setMyLocationEnabled(true);
notifLokasi();
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);
} if (googleMap != null){
googleMap.setOnMapClickListener(this);
googleMap.setMyLocationEnabled(true);
}
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
public void notifLokasi(){
LatLng BLENDUK = new LatLng(-6.968213698041749,110.42742323130369);
Marker blenduk = googleMap.addMarker(new MarkerOptions()
.position(BLENDUK)
.title("Sejarah-Gereja Blenduk")
.icon(BitmapDescriptorFactory.fromResource(R.mipmap.mksj1))
.snippet("Gereja Blenduk,Semarang Kota Lama"));
LatLng jiwasraya = new LatLng(-6.9686366862013776,110.42737729847431);
Marker JiwasRaya = googleMap.addMarker(new MarkerOptions()
.position(jiwasraya)
.title("Sejarah-Gedung Jiwasraya")
.icon(BitmapDescriptorFactory.fromResource(R.mipmap.mksj2))
.snippet("Gedung Jiwasraya,Kota Lama,Semarang"));
LatLng Mberok = new LatLng(-6.968722215625485,110.42517822235823);
Marker mberok = googleMap.addMarker(new MarkerOptions()
.position(Mberok)
.title("Sejarah-Jembatan Mberok")
.icon(BitmapDescriptorFactory.fromResource(R.mipmap.mksj3))
.snippet("Jembatan Mberok,Kota Lama,Semarang"));
LatLng GMandiri = new LatLng(-6.968400731405668,110.42524963617325);
Marker gmandiri = googleMap.addMarker(new MarkerOptions()
.position(GMandiri)
.title("Sejarah-Gedung Mandiri")
.icon(BitmapDescriptorFactory.fromResource(R.mipmap.mksj4))
.snippet("Gedung Mandiri,Kota Lama,Semarang"));
LatLng Lyod = new LatLng(-6.968154126901272,110.42524795979261);
Marker lyod = googleMap.addMarker(new MarkerOptions()
.position(Lyod)
.title("Sejarah-Djakarta Lyod")
.icon(BitmapDescriptorFactory.fromResource(R.mipmap.mksj5))
.snippet("Djakarta Lyod,Kota Lama,Semarang"));
LatLng Tawang = new LatLng(-6.964333238108265,110.42773302644491);
Marker tawang = googleMap.addMarker(new MarkerOptions()
.position(Tawang)
.title("Sejarah-Stasiun Tawang")
.icon(BitmapDescriptorFactory.fromResource(R.mipmap.mksj6))
.snippet("Stasiun Tawang,Kota Lama,Semarang"));
LatLng Prau = new LatLng(-6.966292108945976,110.4271499812603);
Marker prau = googleMap.addMarker(new MarkerOptions()
.position(Prau)
.title("Sejarah-Pabrik Rokok Praoe Lajar")
.icon(BitmapDescriptorFactory.fromResource(R.mipmap.mksj7))
.snippet("Pabrik Rokok Prau Lajar,Kota Lama,Semarang"));
LatLng MrBunta = new LatLng(-6.965792574363458,110.42972389608622);
Marker mrbunta = googleMap.addMarker(new MarkerOptions()
.position(MrBunta)
.title("Sejarah-Gedung Marabunta")
.icon(BitmapDescriptorFactory.fromResource(R.mipmap.mksj8))
.snippet("Gedung Marabunta,Kota Lama,Semarang"));
LatLng Marba = new LatLng(-6.968545499171693,110.42803511023521);
Marker marba = googleMap.addMarker(new MarkerOptions()
.position(Marba)
.title("Sejarah-Gedung Marba")
.icon(BitmapDescriptorFactory.fromResource(R.mipmap.mksj9))
.snippet("Gedung Marba,Kota Lama,Semarang"));
LatLng Angkringa = new LatLng(-6.968192731663565,110.42823124676943);
Marker angkringan = googleMap.addMarker(new MarkerOptions()
.position(Angkringa)
.title("Sejarah-Angkringa Blenduk")
.icon(BitmapDescriptorFactory.fromResource(R.mipmap.mkul1))
.snippet("Angkringan Blenduk,Kota Lama,Semarang"));
LatLng Sate = new LatLng(-6.968576782315264,110.42772129178047);
Marker sate = googleMap.addMarker(new MarkerOptions()
.position(Sate)
.title("Kuliner-Sate Kambing 29")
.icon(BitmapDescriptorFactory.fromResource(R.mipmap.mkkl2))
.snippet("Sate Kambing 29,Kota Lama,Semarang"));
LatLng IBC = new LatLng(-6.9686985868756475,110.42686466127634);
Marker ibc = googleMap.addMarker(new MarkerOptions()
.position(IBC)
.title("Kuliner-Ikan Bakar Cianjur")
.icon(BitmapDescriptorFactory.fromResource(R.mipmap.mkkl3))
.snippet("Ikan Bakar Cianjur,Kota Lama,Semarang"));
LatLng Cafe = new LatLng(-6.967544437475304,110.4279100522399);
Marker cafe = googleMap.addMarker(new MarkerOptions()
.position(Cafe)
.title("Kuliner-Retro Cafe")
.icon(BitmapDescriptorFactory.fromResource(R.mipmap.mkkl4))
.snippet("Retro Cafe,Kota Lama,Semarang"));
LatLng SCAG = new LatLng(-6.967490523852544,110.42818564921618);
Marker scag = googleMap.addMarker(new MarkerOptions()
.position(SCAG)
.title("Rekreasi-Semarang Contenporer Art Gallery")
.icon(BitmapDescriptorFactory.fromResource(R.mipmap.mkrk1))
.snippet("Semarang Contenporer Art Gallery,Kota Lama,Semarang"));
LatLng Srigunting = new LatLng(-6.968171099685091,110.42781382799149);
Marker srigunting = googleMap.addMarker(new MarkerOptions()
.position(Srigunting)
.title("Rekreasi-Taman Srigunting")
.icon(BitmapDescriptorFactory.fromResource(R.mipmap.mkrk2))
.snippet("Taman Srigunting,Kota Lama,Semarang"));
LatLng PTawang = new LatLng(-6.9653346394619021,110.42811222374439);
Marker ptawang = googleMap.addMarker(new MarkerOptions()
.position(Srigunting)
.title("Rekreasi-Polder Tawang")
.icon(BitmapDescriptorFactory.fromResource(R.mipmap.mkrk2))
.snippet("Polder Tawang,Kota Lama,Semarang"));
}
#Override
public void onMapClick(LatLng latLng) {
googleMap.clear();
latAwal = latLng.latitude;
lngAwal = latLng.longitude;
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(latAwal,lngAwal))
.title("Start Perjalanan")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_marker))
);
notifLokasi();
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
#OnClick(R.id.fab)
public void onFabClick() {
data = getIntent().getExtras();
Tujuan = data.getString("Tujuan");
if (Tujuan.equals("Gereja Blenduk")) {
latTujuan = -6.968213698041749;
lngTujuan = 110.42742323130369;
} else if (Tujuan.equals("Gedung Jiwasraya")) {
latTujuan = -6.9686366862013776;
lngTujuan = 110.42737729847431;
} else if (Tujuan.equals("Jembatan Mberok")) {
latTujuan = -6.968722215625485;
lngTujuan = 110.42517822235823;
} else if (Tujuan.equals("Gedung Mandiri")) {
latTujuan = -6.968400731405668;
lngTujuan = 110.42524963617325;
} else if (Tujuan.equals("Djakarta Lyod")) {
latTujuan = -6.968154126901272;
lngTujuan = 110.42524795979261;
} else if (Tujuan.equals("Stasiun Tawang")) {
latTujuan = -6.964333238108265;
lngTujuan = 110.42773302644491;
} else if (Tujuan.equals("Pabrik Rokok Praoe Lajar")) {
latTujuan = -6.966292108945976;
lngTujuan = 110.4271499812603;
} else if (Tujuan.equals("Gedung Marabunta")) {
latTujuan = -6.965792574363458;
lngTujuan = 110.42972389608622;
} else if (Tujuan.equals("Gedung Marba")) {
latTujuan = -6.968545499171693;
lngTujuan = 110.42803511023521;
} else if (Tujuan.equals("Angkringan Blenduk")) {
latTujuan = -6.968192731663565;
lngTujuan = 110.42823124676943;
} else if (Tujuan.equals("Sate Kambing 29")) {
latTujuan = -6.968576782315264;
lngTujuan = 110.42772129178047;
} else if (Tujuan.equals("Ikan Bakar Cianjur")) {
latTujuan =-6.9686985868756475;
lngTujuan = 110.42686466127634;
} else if (Tujuan.equals("Retro Cafe")) {
latTujuan = -6.967544437475304;
lngTujuan = 110.4279100522399;
} else if (Tujuan.equals("SEMARANG ART GALLERY")) {
latTujuan = -6.967490523852544;
lngTujuan = 110.42818564921618;
} else if (Tujuan.equals("Taman Srigunting")) {
latTujuan = -6.968171099685091;
lngTujuan = 110.42781382799149;
} else if (Tujuan.equals("PPOLDER TAWANG")) {
latTujuan = -6.9653346394619021;
lngTujuan = 110.42811222374439;
}
GoHasilRute();
}
public void GoHasilRute(){
Bundle data = new Bundle();
data.putDouble("latAwal", latAwal);
data.putDouble("lngAwal", lngAwal);
data.putDouble("latTujuan", latTujuan);
data.putDouble("lngTujuan", lngTujuan);
data.putString("Tujuan", Tujuan);
startActivity(new Intent(this, ViewRouteActivity.class).putExtras(data));
}
}
I want to get Current location,with GPS is On,
but in Android 5.0.2 , Device Sony Z1 , GPS cannot automaticly On ,
in other device Himax 4.4,Huawei , ZenFone , this is work.
Updated:
Parshant , I Call function OnCreate
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//show error dialog if GoolglePlayServices not available
if (!isGooglePlayServicesAvailable()) {
finish();
}
setContentView(R.layout.activity_add_map);
ButterKnife.inject(this);
// progressDialog = new ProgressDialog(this);
// progressDialog.setMessage("Mendapatkan Lokasi Saya.. Tunggu");
// progressDialog.show();
GPSTracker gps = new GPSTracker(AddMapActivity.this);
if (gps.canGetLocation()) {
}
else {
gps.showSettingsAlert();
}
setUpMapIfNeeded();
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog
.setMessage("Please allow access of location to get current location. To re-enable, please go to Settings and turn on Location Service for this app.");
// On pressing Settings button
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
I'm trying to detect if a user is in the radius of a Marker , using the users gps location. I have the marker's coordinates, but I don't know how to calculate whether the user is in the area. I've tried to use the following, but even when the current location is inside the circle I keep getting the "outside" message.
public class MapaEscola extends FragmentActivity {
private GoogleMap googleMap;
private Serializable escolas;
private ProgressDialog dialog;
private Circle mCircle;
private Marker mMarker;
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
setContentView(R.layout.maps);
// Loading map
initilizeMap();
// Changing map type
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// Showing / hiding your current location
googleMap.setMyLocationEnabled(true);
// Enable / Disable zooming controls
googleMap.getUiSettings().setZoomControlsEnabled(true);
// Enable / Disable my location button
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
// Enable / Disable Compass icon
googleMap.getUiSettings().setCompassEnabled(true);
// Enable / Disable Rotate gesture
googleMap.getUiSettings().setRotateGesturesEnabled(true);
// Enable / Disable zooming functionality
googleMap.getUiSettings().setZoomGesturesEnabled(true);
Bundle extra = getIntent().getBundleExtra("extra");
ArrayList<Escolas> objects = (ArrayList<Escolas>) extra.getSerializable("array");
try {
for(int i = 0; i < objects.size(); i ++) {
System.out.println(" escolas " + objects.get(i).getLatitude() + " " + objects.get(i).getLongitude());
float latitude = objects.get(i).getLatitude();
float longitude = objects.get(i).getLongitude();
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-23.316281, -51.155528), 15));
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(new LatLng(latitude, longitude));
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
LatLng latLng = new LatLng(latitude, longitude);
drawMarkerWithCircle(latLng);
googleMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
float[] distance = new float[2];
Location.distanceBetween( mMarker.getPosition().latitude, mMarker.getPosition().longitude,
mCircle.getCenter().latitude, mCircle.getCenter().longitude, distance);
if( distance[0] > (mCircle.getRadius() / 2) ){
Toast.makeText(getBaseContext(), "Outside", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "Inside", Toast.LENGTH_LONG).show();
}
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void drawMarkerWithCircle(LatLng position){
double radiusInMeters = 500.0;
int strokeColor = 0xffff0000; //red outline
int shadeColor = 0x44ff0000; //opaque red fill
CircleOptions circleOptions = new CircleOptions().center(position).radius(radiusInMeters).fillColor(shadeColor).strokeColor(strokeColor).strokeWidth(8);
mCircle = googleMap.addCircle(circleOptions);
MarkerOptions markerOptions = new MarkerOptions().position(position);
mMarker = googleMap.addMarker(markerOptions);
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Não foi possível carregar o mapa", Toast.LENGTH_SHORT)
.show();
}
}
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
super.onBackPressed();
finish();
return true;
}
return true;
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
}
I just ran the updated code and figured out what the main problem is.
You should be using the Location passed into the onMyLocationChange() callback, so that it uses your current location to tell if the device is within the circle or not:
googleMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
float[] distance = new float[2];
/*
Location.distanceBetween( mMarker.getPosition().latitude, mMarker.getPosition().longitude,
mCircle.getCenter().latitude, mCircle.getCenter().longitude, distance);
*/
Location.distanceBetween( location.getLatitude(), location.getLongitude(),
mCircle.getCenter().latitude, mCircle.getCenter().longitude, distance);
if( distance[0] > mCircle.getRadius() ){
Toast.makeText(getBaseContext(), "Outside, distance from center: " + distance[0] + " radius: " + mCircle.getRadius(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "Inside, distance from center: " + distance[0] + " radius: " + mCircle.getRadius() , Toast.LENGTH_LONG).show();
}
}
});
Here is the full working example that I ran, it's a pared down version of your original code:
public class MainActivity extends ActionBarActivity {
private GoogleMap googleMap;
private Serializable escolas;
private ProgressDialog dialog;
private Circle mCircle;
private Marker mMarker;
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
setContentView(R.layout.activity_main);
// Loading map
initilizeMap();
// Changing map type
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// Showing / hiding your current location
googleMap.setMyLocationEnabled(true);
// Enable / Disable zooming controls
googleMap.getUiSettings().setZoomControlsEnabled(true);
// Enable / Disable my location button
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
// Enable / Disable Compass icon
googleMap.getUiSettings().setCompassEnabled(true);
// Enable / Disable Rotate gesture
googleMap.getUiSettings().setRotateGesturesEnabled(true);
// Enable / Disable zooming functionality
googleMap.getUiSettings().setZoomGesturesEnabled(true);
// Bundle extra = getIntent().getBundleExtra("extra");
//ArrayList<Escolas> objects = (ArrayList<Escolas>) extra.getSerializable("array");
try {
//test outside
double mLatitude = 37.77657;
double mLongitude = -122.417506;
//test inside
//double mLatitude = 37.7795516;
//double mLongitude = -122.39292;
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLatitude, mLongitude), 15));
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(new LatLng(mLatitude, mLongitude));
//googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
LatLng latLng = new LatLng(mLatitude, mLongitude);
drawMarkerWithCircle(latLng);
googleMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
float[] distance = new float[2];
/*
Location.distanceBetween( mMarker.getPosition().latitude, mMarker.getPosition().longitude,
mCircle.getCenter().latitude, mCircle.getCenter().longitude, distance);
*/
Location.distanceBetween( location.getLatitude(), location.getLongitude(),
mCircle.getCenter().latitude, mCircle.getCenter().longitude, distance);
if( distance[0] > mCircle.getRadius() ){
Toast.makeText(getBaseContext(), "Outside, distance from center: " + distance[0] + " radius: " + mCircle.getRadius(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "Inside, distance from center: " + distance[0] + " radius: " + mCircle.getRadius() , Toast.LENGTH_LONG).show();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
private void drawMarkerWithCircle(LatLng position){
double radiusInMeters = 500.0;
int strokeColor = 0xffff0000; //red outline
int shadeColor = 0x44ff0000; //opaque red fill
CircleOptions circleOptions = new CircleOptions().center(position).radius(radiusInMeters).fillColor(shadeColor).strokeColor(strokeColor).strokeWidth(8);
mCircle = googleMap.addCircle(circleOptions);
MarkerOptions markerOptions = new MarkerOptions().position(position);
mMarker = googleMap.addMarker(markerOptions);
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(
R.id.map)).getMap();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Não foi possível carregar o mapa", Toast.LENGTH_SHORT)
.show();
}
}
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
super.onBackPressed();
finish();
return true;
}
return true;
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
}
Results of Inside the circle:
Results of outside the circle:
#Daniel Nugent:
imho getRadius() will return the radius and not the diameter so the "/2" is wrong
#WARpoluido:
I cant see that the mMarker variable is updated when the location changes. Why dont you use the value given to onMyLocationChange()?
Location.distanceBetween( mCircle.getCenter().latitude, mCircle.getCenter().longitude, location.getLatitude(), location.getLongitude(), distance);
if( distance[0] > mCircle.getRadius() ){
...
Hi I have got mine working correctly with this code
//Getting current location
private void getCurrentLocation() {
mMap.clear();
//Creating a location object
Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (location != null) {
//Getting longitude and latitude
longitude = location.getLongitude();
latitude = location.getLatitude();
//moving the map to location
moveMap();
}
Circle circle = mMap.addCircle(new CircleOptions()
.center(new LatLng(54.773097, -6.557841))
.radius(55)
.strokeColor(Color.RED)
);
pLong = location.getLongitude();
pLat = location.getLatitude();
float[] distance = new float[2];
Location.distanceBetween(pLat, pLong,
circle.getCenter().latitude, circle.getCenter().longitude, distance);
if( distance[0] > circle.getRadius() ){
Toast.makeText(getBaseContext(), "You are not in a bunker", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "You are inside a bunker", Toast.LENGTH_LONG).show();
}
}
Inside the circle
Outside the circle
The accepted solution of Daniel Nugent isn't so good anymore because setOnMyLocationChangeListener is deprecated now.
Here is current way how to do it in fragment - change getActivity() with this for Activity:
private boolean mLocationPermissionGranted;
// The geographical location where the device is currently located. That is, the last-known
// location retrieved by the Fused Location Provider.
private Location mLastKnownLocation;
private long UPDATE_INTERVAL = 10 * 1000; /* 10 secs */
private long FASTEST_INTERVAL = 2000; /* 2 sec */
private FusedLocationProviderClient mFusedLocationProviderClient;
private void addLocationChangeListener(){
// Construct a FusedLocationProviderClient.
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getActivity());
// Create the location request to start receiving updates
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
//mLocationRequest.setMaxWaitTime(0);
//mLocationRequest.setSmallestDisplacement(0);
// Create LocationSettingsRequest object using location request
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest);
LocationSettingsRequest locationSettingsRequest = builder.build();
// Check whether location settings are satisfied
// https://developers.google.com/android/reference/com/google/android/gms/location/SettingsClient
SettingsClient settingsClient = LocationServices.getSettingsClient(getActivity());
settingsClient.checkLocationSettings(locationSettingsRequest);
// new Google API SDK v11 uses getFusedLocationProviderClient(this)
if (mLocationPermissionGranted) {
mFusedLocationProviderClient.requestLocationUpdates(mLocationRequest,
new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
// do work here
Location location = locationResult.getLastLocation();
}
},
Looper.myLooper());
} else {
getLocationPermission();
}
}
I've implemented a clustermarker in my app, I have a list of LatLng that comes from my database, now I want to show the name of the clients as title when the user clicks on the marker,but when I click on the marker it shows me nothing, how can I achieve that, this is my code so far:
public class MapaViagem extends FragmentActivity {
private GoogleMap googleMap;
private String rm_IdViagem;
private List<ClienteModel> mClienteModel = new ArrayList<ClienteModel>();
private List<EnderecoModel> mEnderecoModel = new ArrayList<EnderecoModel>();
private ViagemModel mViagemModel = new ViagemModel();
private ClusterManager<MyItem> mClusterManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps);
ArrayList<LatLng> coordList = new ArrayList<LatLng>();
try {
Bundle parametros = getIntent().getExtras();
rm_IdViagem = parametros.getString("id_viagem");
Repositorio ca = new Repositorio(this);
mViagemModel = ca.getViagemPorId(Integer.valueOf(rm_IdViagem));
Repositorio cl = new Repositorio(this);
mClienteModel = cl.getClientesViagem(Integer.valueOf(rm_IdViagem));
int i;
for ( i = 0; i < mClienteModel.size(); i++) {
Repositorio mRepositorio = new Repositorio(this);
mEnderecoModel = mRepositorio.getListaEnderecosDoCliente(Integer.valueOf(mClienteModel.get(i).getClientes_id()));
System.out.println("NOMES " + mClienteModel.get(i).getNome());
for (int j = 0; j < mEnderecoModel.size(); j++) {
// Loading map
initilizeMap();
// Changing map type
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
// googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
// googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);
// Showing / hiding your current location
googleMap.setMyLocationEnabled(true);
// Enable / Disable zooming controls
googleMap.getUiSettings().setZoomControlsEnabled(true);
// Enable / Disable my location button
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
// Enable / Disable Compass icon
googleMap.getUiSettings().setCompassEnabled(true);
// Enable / Disable Rotate gesture
googleMap.getUiSettings().setRotateGesturesEnabled(true);
// Enable / Disable zooming functionality
googleMap.getUiSettings().setZoomGesturesEnabled(true);
final float latitude = Float.parseFloat(mEnderecoModel.get(j).getLatitude());
final float longitude = Float.parseFloat(mEnderecoModel.get(j).getLongitude());
coordList.add(new LatLng(latitude, longitude));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 10));
// Initialize the manager with the context and the map.
// (Activity extends context, so we can pass 'this' in the constructor.)
mClusterManager = new ClusterManager<MyItem>(this, googleMap);
// Point the map's listeners at the listeners implemented by the cluster
// manager.
googleMap.setOnCameraChangeListener(mClusterManager);
googleMap.setOnMarkerClickListener(mClusterManager);
addItems(coordList);
googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(final Marker marker) {
LatLng pos = marker.getPosition();
int arryListPosition = getArrayListPosition(pos);
return true;
}
});
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private int getArrayListPosition(LatLng pos) {
for (int i = 0; i < mEnderecoModel.size(); i++) {
if (pos.latitude == Double.parseDouble(mEnderecoModel.get(i).getLatitude().split(",")[0])) {
if (pos.longitude == Double.parseDouble(mEnderecoModel.get(i).getLongitude().split(",")[1]))
return i;
}
}
return 0;
}
private void addItems(List<LatLng> markers) {
for (int i = 0; i < markers.size(); i++) {
MyItem offsetItem = new MyItem(markers.get(i));
mClusterManager.addItem(offsetItem);
}
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Não foi possível carregar o mapa", Toast.LENGTH_SHORT)
.show();
}
}
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
}
Not sure how you are initializing your Markers because you don't show that part of the code but put a title on it is done this way:
//You need a reference to a GoogleMap object
GoogleMap map = ... // get a map.
Marker marker = map.addMarker(new MarkerOptions()
.position(new LatLng(37.7750, 122.4183)) //Or whatever coordinate
.title("Your title")
.snippet("Extra info"));
And that's it, when you click it you'll see the info of that marker.
You can find more information here
EDIT
For the ClusterManagerI think you can find this answer helpful