I use Google Map Android API v2 in my app and I have a little problem as in the picture below but have no ideas how to fix it. I set marker to current location of device but its now in the center of circle. I want to set marker to the center of the circle. Is it possible or not?
Thanks for any help!
Code that I used:
// Showing status
if(status!= ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}else { // Google Play Services are available
// Getting reference to the SupportMapFragment of activity_location.xml
SupportMapFragment mSupportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
mGoogleMap = mSupportMapFragment.getMap();
// Enabling MyLocation Layer of Google Map
mGoogleMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = mLocationManager.getBestProvider(criteria, true);
// Getting Current Location
Location location = mLocationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
mLocationManager.requestLocationUpdates(provider, 20000, 0, this);
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng mLatLng = new LatLng(latitude, longitude);
//Add Marker to current location of devise
mGoogleMap.addMarker(new MarkerOptions()
.position(mLatLng)
.title("Geolocation system")
.snippet("Your last current location which was available!"));
// .icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_location)));
// Showing the current location in Google Map
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(mLatLng));
// Show Zoom buttons
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
// Turns on 3D buildings
mGoogleMap.setBuildingsEnabled(true);
// Zoom in the Google Map
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(14));
You are getting your location using GPS and network. these are not giving your correct location and you are using:-
mGoogleMap.setMyLocationEnabled(true);
this showing your location using google map api. so the loaction by you and google are different .so circle and marker are showing different location.
so you can use google's Fuesed Location client for this
Visit this for more help.
https://developer.android.com/reference/com/google/android/gms/location/FusedLocationProviderApi.html
Related
i tried this but its showing my current location first time i get information that i am inside or not . but when i moved outside of radius of point 1 its doesn't showing anything.
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//drawing marker
LatLng pointOne = new LatLng(23.10,72.50847684);
mMap.addMarker(new MarkerOptions().position(pointOne).title("Point 1"));
mMap.addMarker(new MarkerOptions().position(new LatLng(0,0)).title("Point 2").snippet("N"));
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
// Get LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Get Current Location
Location myLocation = locationManager.getLastKnownLocation(provider);
//myLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double latitude = myLocation.getLatitude();
Log.e("latitude", String.valueOf(latitude));
// Get longitude of the current location
double longitude = myLocation.getLongitude();
// Create a LatLng object for the current location
LatLng pointTwo = new LatLng(latitude, longitude);
// Show the current location in Google Map
mMap.moveCamera(CameraUpdateFactory.newLatLng(pointTwo)); Log.e("location", String.valueOf(pointTwo));
//drawing overlay circle on marker
Circle circle = mMap.addCircle(new CircleOptions()
.center(pointOne)
.radius(5000)
.strokeColor(0x40FF0000)
.fillColor(0x35FF0000));
//for Checking marker is inside or not
float[] distance = new float[2];
Location.distanceBetween( pointTwo.latitude, pointTwo.longitude,
circle.getCenter().latitude, circle.getCenter().longitude, distance);
if( distance[0] > circle.getRadius() ){
Toast.makeText(getBaseContext(), "Outside", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "Inside", Toast.LENGTH_LONG).show();
}
pointToPosition(pointOne);
}
Thanks for Help In advance
You can Use Google GeoFencing API to draw a virtual circle of some radius around the location.On user's entry/exit an event will be triggered which will help your cause.
Now getLastKnownLocation() which you are using May or May Not provide a location value. LocationManager maintains GPS location data until that data becomes outdate in like 8mins odd. After this, there will again be a cold startup and the GPS in your phone will try to get a fix and return results.
In case this is a cold startup, you can also get a NullPointerException because of the fact that the your last know location is outdated.
You can try a requestLocationUpdates() .... if lastKnownLocation returns a Null result...
This will cause the LocationManager to explicitly call the GPS in your phone to search for the current location... this will provide results in a callback function onLocationChanged... here you can get the current location....
This question already has answers here:
My current location always returns null. How can I fix this?
(7 answers)
Closed 7 years ago.
Hi I need some help with this, I have already looked and try many different things. I'm trying to get my current location on android but since the location comes back null my app crashes. I really need help with this please.
I don't know if I'm being clear in here but everytime I call getLastKnownlocation it comes back null, so when I try to get the double lat= location.getLatitude() same for the longitude it won't return anything and there is where my app crashes.
Help...
Here a piece of code
mMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
double lat = location.getLatitude();
double lng = location.getLongitude();
LatLng latLng = new LatLng(lat, lng);
at latitude is where it stops.
Do you retrieve the GoogleMap object from the fragment before calling those functions?
Something like:
//get map fragment from the static layout (in this case it has id = "map")
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
//get GoogleMap object, then you can start using it, for example enabling the location
map = mapFragment.getMap();
map.setMyLocationEnabled(true);
Thank you all for your help I appreciate it, I have already solved my problem.
Here a piece of code that helped me get ti done:
//I needed to have this line before everything else for me to get my current
//location from getLastKnownLocation method.
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker").snippet("Snippet"));
//And the all the codes I had before
mMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
double lat = location.getLatitude();
double lng = location.getLongitude();
LatLng latLng = new LatLng(lat, lng);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(14));
mMap.addMarker(new MarkerOptions()
.position(new LatLng(lat, lng))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.title("Here"));
i have integrated google map in android. and i am getting current location using GPS. on Onlocationchanged i am updating the current location.
My doubt is i am on the Google map UI . i wants to walk or drive that time from my current location as starting point and i wants to start draw the line on map dynamically.
i searched on net for long time but i am not getting any solution . here is my code please anyone help me to over come this problem.
private void initalizeMap()
{
// Google Play Services are available
// Getting GoogleMap object from the fragment
googleMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map)).getMap();
if(gps.canGetLocation())
{
double latitude = Double.valueOf(Helper.loadSavedPreferences(getActivity(), NameConversion.LATITUDE));
double longtitude = Double.valueOf(Helper.loadSavedPreferences(getActivity(), NameConversion.LONGITUDE));
Log.d("getting gps value", ""+ latitude);
Log.d("getting gps Long", ""+ longtitude);
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longtitude);
// create marker
marker = new MarkerOptions().position(latLng).title("You are here!");
// Changing marker icon
// set yours icon here
marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_green_point));
// Showing the current location in Google Map
googleMap.setTrafficEnabled(true);
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(25));
googleMap.addMarker(marker);
}else{
Toast.makeText(getActivity(), "failed To get the location", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onLocationChanged(Location location) {
double latitude = gps.getLatitude();
// Getting longitude of the current location
double longitude = gps.getLongitude();
// Creating a LatLng object for the current location
Log.d("latitude map Class", "latitude: " + gps.getLatitude());
Log.d("longitude Map CLass", "longitude: " + gps.getLongitude());
LatLng latLng = new LatLng(latitude, longitude);
// create marker
MarkerOptions marker = new MarkerOptions().position(latLng).title("You are here!");
// Changing marker icon
// set yours icon here
marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_green_point));
// Showing the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(25));
}
and i tried with following links [1 st lnikn second link
In order to get the drive or walking time on Google maps you have to make use of the Direction API's provided by Google. The API call for the Direction would would something like this:
http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los%20Angeles,CA&sensor=false
And you can embed that inside a class where you would make an http call using AsyncTask which would look like this:
GenericUrl url = new GenericUrl("http://maps.googleapis.com/maps/api/directions/json");
url.put("origin", origin);
url.put("destination", destination);
url.put("sensor",false);
Please follow this tutorial or this in order get the direction API (that includes driving, transit. walking and bicycling direction on your maps. )
Hope that would help!!!
I want to stop the LocationListener once it has the current location and zoomed to it.
Can you please help a newbie?
Here's my code:
#Override
public void onMyLocationChange(Location location) {
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
}
Set the map location listener to null to turn it off.
mMap.setOnMyLocationChangeListener(null);
Sadly,the above solution did not work for me,
I had to add:
mMap.setMyLocationEnabled(false);
i want to make a program to calculate the distance between some places to my current location, but my googleMap.getMyLocation(); doesnt work properly.
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setCompassEnabled(false);
mylocation = googleMap.getMyLocation();
direction = new GMapV2Direction();
LatLng from, to;
from = new LatLng(-7.26071409, 112.80674726);
for(int i=0; i<lat.length; i++){
to = new LatLng(lat[i], lon[i]);
doc = direksi.getDocument(from, to, GMapV2Direction.MODE_DRIVING);
distance[i] = (double)direction.getDistanceValue(doc) / 1000;
}
i saved the latitude and longitude of some places in lat[] and lon[].
LatLng 'from' is mylocation and 'to' is my destination places.
the problem appear when i change
from = new LatLng(-7.26071409, 112.80674726);
to
from = new LatLng(mylocation.getLatitude(), mylocation.getLongitude());
i want to do the calculation without opening the googlemaps. the google maps will appear when i touch the map button as pop up window. so the calculation will happen without opening googlemap
please help me
Try this...I hope this will be help to you
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager
.getBestProvider(criteria, false));
double latitude = location.getLatitude();
double longitude = location.getLongitude();
This is my code for you, I hope this help you... edit it if you think, it isn't with correct sintaxis...
This work for android 4.x and 5.x and 6.x, I not test this in android 7
//I use this like global var to edit or get informacion about google map
GoogleMap gMap;
#Override
public void onMapReady(GoogleMap googleMap) {
gMap = googleMap;
if (ActivityCompat.checkSelfPermission(Activity_Map.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(Activity_Map.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(Activity_Map.this,new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}else{
if(!gMap.isMyLocationEnabled())
gMap.setMyLocationEnabled(true);
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location myLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (myLocation == null) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
String provider = lm.getBestProvider(criteria, true);
myLocation = lm.getLastKnownLocation(provider);
}
if(myLocation!=null){
LatLng userLocation = new LatLng(myLocation.getLatitude(), myLocation.getLongitude());
gMap.animateCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 14), 1500, null);
}
}
}
getMyLocation() => this method is deprecated. You need to use LocationClient instead.
You can find informations about LocationClient and how to get current location here