I am having trouble using the loactionListener in eclipse for android. I have been googling for a while now an I can't seem to see why this shouldn't work. The only thing I can think of is that maybe it is because my testing device has no sim. (the internet is provided via wifi).
I have used this as a reference and still, nothing.
Could anyone help me with this problem.
here is the relevant parts of my activity:
public class MainMenu extends Activity implements LocationListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu);
theMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.the_map)).getMap();
theMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
locMan = (LocationManager)getSystemService(LOCATION_SERVICE);
}
#Override
public void onLocationChanged(Location location) {
final Double lat = location.getLatitude();
final Double lng = location.getLongitude();
LatLng lastLatLng = new LatLng(lat, lng);
String title = getString(new StringLang().textSet(userLang,"marker_title"));
String snippit = getString(new StringLang().textSet(userLang,"marker_snip"));
if(userMarker!=null) userMarker.remove();
userMarker = theMap.addMarker(new MarkerOptions()
.position(lastLatLng)
.title(title)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher))
.snippet(snippit));
reverseGeoCode(lat, lng);
}
}
I was using a different method to display my location on the map, which worked well but it never updated. It always showed my location at the last place I used the GPS, which turns out was 60mile accross the country. I can see this is working but is there a better way of doing this.
Old method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu);
if(findViewById(R.id.the_map) != null){
//map has loaded continue
theMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.the_map)).getMap();
theMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
android.location.Location lastLoc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
LatLng lastLatLng ;
if(lastLoc == null){
/* Use the LocationManager class to obtain GPS locations */
double latitude = 0;
double longitude = 0;
lastLatLng = new LatLng(latitude, longitude);
lat = latitude;
lng = longitude;
String title = getString(new StringLang().textSet(userLang,"marker_title"));
String snippit = getString(new StringLang().textSet(userLang,"marker_snip"));
if(userMarker!=null) userMarker.remove();
userMarker = theMap.addMarker(new MarkerOptions()
.position(lastLatLng)
.title(title)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.your_loc_icon))
.snippet(snippit));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(lastLatLng) // Sets the center of the map to user position
.zoom(0) // Sets the zoom
.bearing(90) // Sets the orientation of the camera to east
.tilt(20) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
currentLoc = lastLatLng;
theMap.animateCamera (CameraUpdateFactory.newCameraPosition(cameraPosition), 3000, null);
final TextView geoTagText = (TextView)findViewById(R.id.text_geoTag);
geoTagText.setText("We cannot find your current location, please check your settings.");
}else{
double latitude = lastLoc.getLatitude();
double longitude = lastLoc.getLongitude();
lastLatLng = new LatLng(latitude, longitude);
lat = latitude;
lng = longitude;
animateMap(lastLatLng);
}
}else{
theMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.the_map)).getMap();
theMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
android.location.Location lastLoc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
LatLng lastLatLng;
double latitude = lastLoc.getLatitude();
double longitude = lastLoc.getLongitude();
lastLatLng = new LatLng(latitude, longitude);
lat = latitude;
lng = longitude;
animateMap(lastLatLng);
//no map to load
}
}
#Override
public void onLocationChanged(Location location) {
final Double lat = location.getLatitude();
final Double lng = location.getLongitude();
LatLng lastLatLng = new LatLng(lat, lng);
String title = getString(new StringLang().textSet(userLang,"marker_title"));
String snippit = getString(new StringLang().textSet(userLang,"marker_snip"));
if(userMarker!=null) userMarker.remove();
userMarker = theMap.addMarker(new MarkerOptions()
.position(lastLatLng)
.title(title)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher))
.snippet(snippit));
}
it would also be useful to add that there is button to relocate the user manually if they want.
reLocBtn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
if(menuActive == true){
playSound();
LocationManager loc = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
android.location.Location gpsLoc = (Location) loc.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double lat = gpsLoc.getLatitude();
double lng = gpsLoc.getLongitude();
LatLng lastLatLng = new LatLng(lat, lng);
animateMap(lastLatLng);
}
}
});
I'm not to sure why either method doesn't update, but the second method seams to work better on first load.
You don't appear to be using requestLocationUpdates() anywhere. In that method you pass a LocationListener object that it then calls for location updates.
i.e. in your case:
locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
If you are using Google Maps API v2, you can do it using that, for example:
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
mMarker = mMap.addMarker(new MarkerOptions().position(loc));
if(mMap != null){
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
}
}
};
and then set the listener for the map:
mMap.setOnMyLocationChangeListener(myLocationChangeListener);
This will get called when the map first finds the location.
No need for LocationService or LocationManager at all.
Related
to start with, I am completely confused with various api's available for location and map. So, I even dont know if the code is optimal for sdk 27.(I have minimum sdk 24 set.)
The problem is this piece of code shows the current location well and fine, butand the map gets updated when the location is changed. But, that is not reflected in location. See, the polyline drawn from LatLong does not follow the current location.
Also, I am trying to implement FusedLocationProviderClient but thats probably not the case here.
Any help will be very welcome.
public class SecondFragment extends Fragment implements OnMapReadyCallback {
//Color stroke = new Color(222.0,135.0, 135.0,174.0);
private GoogleMap mMap;
public static SecondFragment newInstance() {
SecondFragment fragment = new SecondFragment();
return fragment;
}
public GoogleMap getMap() {
return mMap;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_second, null, false);
SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
return view;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
double latitude;
double longitude;
LocationManager locationManager = (LocationManager) getActivity().getSystemService(getActivity().LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]
{android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
} else {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null) {
latitude = 0.0;
longitude = 0.0;
} else {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
latlang.Lat = latitude;
latlang.Lang = longitude;
CameraPosition cameraPosition = new CameraPosition.Builder().target(
new LatLng(latitude, longitude)).zoom(18).build();
double angle = Math.toRadians(93.833);
Point cPoint = mMap.getProjection().toScreenLocation(new LatLng(latitude,longitude));
System.out.println("mPoint X"+ cPoint.x);
System.out.println("mPoint Y"+ cPoint.y);
Point mPoint = new Point();
//Azimuth Pos only
double lat_azi = 2*Math.sin(angle)+cPoint.y;
double long_azi = 2*Math.cos(angle)+cPoint.x;
LatLng nat_azi =mMap.getProjection().fromScreenLocation(mPoint);
//private List<Point> mPoint = new ArrayList<Point>();
Marker marker = mMap.addMarker(new MarkerOptions()
.position(nat_azi)
.anchor(0.5f,0.5f)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.sun_pos_icon))
);
Marker marker_loc = mMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.anchor(0.5f, 0.5f)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.location_icon))
);
mMap.addPolyline(new PolylineOptions()
.add(new LatLng(lat_azi, long_azi), new LatLng(latitude, longitude), new LatLng(0,0))
.width(15)
.color(Color.MAGENTA));
PathOfSun.getTime();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
mMap.setMyLocationEnabled(true);
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.getUiSettings().setZoomControlsEnabled(true); // true to enable
googleMap.getUiSettings().setZoomGesturesEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
}
}
}
You can follow below link for Updating Marker position on the Map.
Move marker with gps in google map android
I know that if I use this, I can get my location, but how can I get it automatically or by clicking a button; How can I update my location?
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(this.getLocation(), 16));
MarkerOptions a = new MarkerOptions().position(this.getLocation());
m = mMap.addMarker(a);
}
private LatLng getLocation() {
LatLng location = null;
gps = new GPSTracker(MainActivity.this);
if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
location = new LatLng(latitude, longitude);
return location;
} else {
gps.showSettingsAlert();
location = new LatLng(-23.036602, -13.183594);
return location;
}
}
The only way I could do this was by restarting the activity, but I think this is not the best solution.
how I can get latitude and longitude from setMyLocationEnabled? while my code is this.
I need to use it to zoomin to location,
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0,0)).title("Marker"));
mMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory.newLatLng());
mMap.animateCamera(CameraUpdateFactory.zoomBy(13));
}
For getting individual latitude and longitude, the following works for me.
mMap.setMyLocationEnabled(true);
double lat = mMap.getMyLocation().getLatitude();
double longt = mMap.getMyLocation().getLongitude();
Google map location API has the listeners you can get your current location by using this.
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
mMarker = mMap.addMarker(new MarkerOptions().position(loc));
if(mMap != null){
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
}
}
};
And then set the listener for the map.
mMap.setOnMyLocationChangeListener(myLocationChangeListener);
I am trying to add Google maps in my application. I get maps successfully displayed in my application.
But the Problem is I am not getting my desired position.
static final LatLng vrrittihLocation = new LatLng(23.001779, 72.618946);
private GoogleMap googleMap;
if (googleMap == null) {
googleMap = ((SupportMapFragment) getFragmentManager()
.findFragmentById(R.id.map)).getMap();
}
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
MarkerOptions Mo = new MarkerOptions()
.position(vrrittihLocation)
.title("Vrrittih Global Recruitment Consulting")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_marker));
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(vrrittihLocation, 18);
googleMap.animateCamera(cameraUpdate);
googleMap.addMarker(Mo);
Am I missing something here?
The marker should be on ur maps, the reason u dont see your desired position maybe you can move your camera with following code.
CameraPosition cameraPosition = new CameraPosition.Builder().target(vrrittihLocation)
.zoom(18)
.build();
CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(cameraPosition);
googleMap.animateCamera(cameraUpdate);
Get Latitude and Longitude through LocationManager , Like Following ,
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
TextView locationTv = (TextView) findViewById(R.id.latlongLocation);
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(latLng));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
locationTv.setText("Latitude:" + latitude + ", Longitude:" + longitude);
}
and in overiden method onLocationChanged(...),
#Override
public void onLocationChanged(Location location) {
TextView locationTv = (TextView) findViewById(R.id.latlongLocation);
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(latLng));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
locationTv.setText("Latitude:" + latitude + ", Longitude:" + longitude);
}
Hope this helpful to you...
googleMap.moveCamera(cameraUpdate);
I am trying to find out if the current location of the user is inside a circle. I have this code right now.
Circle circle = map.addCircle(new CircleOptions()
.center(new LatLng(14.635594, 121.032962))
.radius(80)
.strokeColor(Color.RED)
);
map.setOnMyLocationChangeListener(this);
Location.distanceBetween(
circle.getCenter().latitude, circle.getCenter().longitude,pLat,pLong, distance);
if( distance[0] > circle.getRadius() ){
Toast.makeText(getBaseContext(), "Outside", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "Inside", Toast.LENGTH_LONG).show();
}
public void onMyLocationChange(Location location) {
// TODO Auto-generated method stub
pLat = location.getLatitude();
// Getting longitude of the current location
pLong = location.getLongitude();
The toast displays outside even though I am clearly inside the circle. I tried this code
LatLng latlng = new LatLng (pLat,pLong);
QC.contains(latlng);
where QC is a LatLngBounds variable. I wonder if Circle has also contains functionality to know if the user is inside the circle or is there a possible workaround. Thanks!
multiply your latitude and longitude values by 1e6, bcoz those values are in microbytes.
more info about microbyte conversion
if you are using Criteria Please try this
map.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
if (location != null)
{
// this will animate you to the current location
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(),location.getLongitude()), 13));
protected double latti;
protected double longi;
protected double radius;
1/ MainActivity extends Activity implements LocationListener
2/locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,this);
3///Add circle
circle = map.addCircle(new CircleOptions()
.center(new LatLng(47.974593,0.217905))
.radius(80)
.strokeColor(Color.CYAN));
}
4/radius=circle.getRadius();
5/onLocationChanged(Location location) {
latti = location.getLatitude();
longi = location.getLongitude();
float[] distance = new float[1];
Location.distanceBetween(latti,longi,circle.getCenter().latitude,circle.getCenter().longit ude, distance);
showToast(distance[0]);
}
private void showToast(float distance) {
if(distance>radius)
{
remarque="Alarm Out Zone";
}
else{
remarque="Inside Zone";
}
Toast.makeText(getApplicationContext(),"Latitude:"+latti+"\nLongitude:"+longi+"\n"+remarque,Toast.LENGTH_LONG).show();
}