I have an app with google maps with one single activity where a map is displayed. I have a menu that allows me to change the map type from but I would like to have an option to get my current location.
Here's the code of my activity:
package com.example.chiapa_mapas;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.maps.CameraUpdateFactory;
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.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.MenuInflater;
import android.view.MenuItem;
public class MainActivity extends android.support.v4.app.FragmentActivity implements OnMapClickListener, LocationListener{
private GoogleMap mMap;
private Context ctx;
private LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
mMap.setOnMapClickListener(this);
// Enable LocationLayer of Google Map
mMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
}
#Override
public boolean onCreateOptionsMenu(android.view.Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.layout.opcoes, menu);
return true; }
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.normal:
mMap.setMapType(1);
break;
case R.id.satellite:
mMap.setMapType(2);
break;
case R.id.terrain:
mMap.setMapType(3);
break;
case R.id.hybrid:
mMap.setMapType(4);
break;
case R.id.none:
mMap.setMapType(0);
break;
case R.id.posicao_actual:
//mMap.setMapType(0);
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria,true);
// Getting Current Location
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0,(android.location.LocationListener) ctx);
break;
default: return super.onOptionsItemSelected(item);
}
return true;
}
#Override
public void onMapClick(LatLng position) {
// TODO Auto-generated method stub
mMap.addMarker(new MarkerOptions().position(position).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
//double ltt = position.latitude;
//double lgt = position.longitude;
//String msg = "Latitude: " + Double.toString(ltt) + " , Longitude: " + Double.toString(lgt) + "";
//Toast toast = Toast.makeText(ctx, msg, Toast.LENGTH_SHORT);
//toast.show();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
// 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.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
// Setting latitude and longitude in the TextView
locationManager.removeUpdates((android.location.LocationListener) this);
}
}
Can someone help? When I press the option "posicao actual" (current location) it crashes.
Thanks in advance
Chiapa
This works for me:
public void methodName(){
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
android.location.LocationListener locationListener = new android.location.LocationListener() {
public void onLocationChanged(Location location) {
//Any method here
}
public void onStatusChanged (String provider, int status, Bundle extras){}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled (String provider){}
};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0, locationListener);
}
Thanks chiapa.
change
locationManager.requestLocationUpdates(provider, 20000, 0,(android.location.LocationListener) ctx);
to
locationManager.requestLocationUpdates(provider, 20000, 0,this);
and remove updates too
Related
I'm having a slight problem, when I run the app on my phone, my moveCamera is set on my previous location (not on my current one which I'm testing it on), and so is my addCircle (set around my previous location, not my current one).
Here is my code:
public class MapDraw extends FragmentActivity {
static GoogleMap googleMap;
LatLng myPosition;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_g_maps_circle);
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
googleMap = fm.getMap();
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
myPosition = new LatLng(latitude, longitude);
circleDraw(latitude,longitude);
zoomIn(latitude,longitude);
}
}
public void circleDraw(double i, double ii) {
googleMap.addCircle(new CircleOptions()
.center(new LatLng(i, ii))
.radius(1000)
.strokeColor(Color.BLACK)
.strokeWidth(2)
.fillColor(Color.argb(50, 238, 116, 116)));
}
public void zoomIn(double Lat, double Long) {
CameraUpdate center=
CameraUpdateFactory.newLatLng(new LatLng(Lat,Long));
CameraUpdate zoom = CameraUpdateFactory.zoomTo(12);
googleMap.moveCamera(center);
googleMap.animateCamera(zoom);
}
}
I want the moveCamera to be on my current location, and my circle on my current location too.
Any help please? Thanks
implement LocationListener. And on onLocationChanged redraw the circle
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdate;
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.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
public class MapDraw extends FragmentActivity implements LocationListener {
static GoogleMap googleMap;
LocationManager locationManager;
String provider;
LatLng myPosition;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_g_maps_circle);
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
googleMap = fm.getMap();
googleMap.setMyLocationEnabled(true);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
}
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
public void circleDraw(double i, double ii) {
googleMap.addCircle(new CircleOptions().center(new LatLng(i, ii))
.radius(1000).strokeColor(Color.BLACK).strokeWidth(2)
.fillColor(Color.argb(50, 238, 116, 116)));
}
public void zoomIn(double Lat, double Long) {
CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(Lat,
Long));
CameraUpdate zoom = CameraUpdateFactory.zoomTo(12);
googleMap.moveCamera(center);
googleMap.animateCamera(zoom);
}
#Override
public void onLocationChanged(Location location) {
googleMap.clear();// clean the map
Toast.makeText(this, "Location Changed", Toast.LENGTH_SHORT).show();
double latitude = location.getLatitude();
double longitude = location.getLongitude();
myPosition = new LatLng(latitude, longitude);
circleDraw(latitude, longitude);
zoomIn(latitude, longitude);
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
i don't have any idea why my code is not working... I made a ListArray that which keep my CurrentPosition continuosly and draw it with a polyline. here is my code.
MainActivity.java
package com.pondys.limon.touregsys;
import java.util.ArrayList;
import java.util.List;
import com.google.android.gms.maps.CameraUpdate;
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.LatLng;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.SyncStateContract.Constants;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.widget.Toast;
public class MainActivity extends FragmentActivity implements LocationListener {
GoogleMap googleMap;
double latitude,longitude,firstLatitude,firstLongitude;
private ArrayList<LatLng> arrayPoints = null;
PolylineOptions polylineOptions;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Getting reference to the SupportMapFragment of activity_main.xml
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
googleMap = fm.getMap();
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
Location location = locationManager.getLastKnownLocation(provider);
// Getting latitude of the current location
firstLatitude = location.getLatitude();
// Getting longitude of the current location
firstLongitude = location.getLongitude();
CameraUpdate center=
CameraUpdateFactory.newLatLng(new LatLng(latitude,longitude));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(15);
googleMap.moveCamera(center);
googleMap.animateCamera(zoom);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onLocationChanged(Location location) {
// Getting latitude of the current location
latitude = location.getLatitude();
// Getting longitude of the current location
longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng (latitude,longitude);
ArrayList<LatLng> list = new ArrayList<LatLng> ();
list.add(latLng);
// Showing the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
PolylineOptions o = new PolylineOptions ().width(3).color(0xFFEE8888);
for(int i = 0; i<list.size(); i++){
o.add(new LatLng(latitude,longitude));
}
googleMap.addPolyline(o);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
there is no any route showing when i execute it...
You have to do it like this :
Polyline pathOptions = googleMap.addPolyline(new PolylineOptions().add(new LatLng(source_latitude, source_longitude), new LatLng(destination_latitude, destination_longitude)));
// Set the polyline's color to blue
pathOptions.setColor(Color.BLUE);
// Set the polyline's width
pathOptions.setWidth(2);
I am Trying to develop small application in which i am trying to Detect Location.
I am using the following code but i don't know why my application crashes. It show the application stops Unfortunately.
Here is the code. Please tell me if there is any bug and if not then please at least reply.
Thanks.
Here is the Code.
package com.project.kamani.nearby;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class Map extends Activity implements LocationListener{
public GoogleMap google_map;
public List<Address> addresses;
public Geocoder geocoder;
private Location location;
private double lat;
private double lang;
private Criteria criteria;
private LocationManager location_manager;
private String provider;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES=20;//DISTANCE IN METERS
private static final long MIN_TIME_BW_UPDATES=1000*60*1;// TAKES UPDATE AFTER 1 MINUTES
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(isGooglePlayAvailable())
{
criteria=new Criteria();
setContentView(R.layout.mapdemo);
getGoogleMap();
getUserLocation();
//Toast.makeText(this, "Latitude:"+lat+" Longitude:"+lang, Toast.LENGTH_LONG).show();
getAddress(lat,lang);
drawMarker(lat,lang);
}
}
private boolean isGooglePlayAvailable(){
int status=GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if(status==ConnectionResult.SUCCESS)
return true;
else
GooglePlayServicesUtil.getErrorDialog(status, this, 10).show();
return false;
}
private void getGoogleMap(){
if(google_map==null){
google_map=((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
}
}
private void drawMarker(double lattitude,double longitude){
google_map.clear();
google_map.setMyLocationEnabled(true);
LatLng latlng=new LatLng(lattitude, longitude);
google_map.moveCamera(CameraUpdateFactory.newLatLng(latlng));
google_map.animateCamera(CameraUpdateFactory.zoomTo(15));
LatLng currentPosition = new LatLng(lattitude,longitude);
google_map.addMarker(new MarkerOptions().position(currentPosition).snippet("Address:" + addresses.get(0).getAddressLine(0) + "City:"+ addresses.get(0).getAddressLine(1)+"Country:"+addresses.get(0).getAddressLine(2)).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)).title("ME"));
}
private void getAddress(double lattitude,double longitude){
geocoder=new Geocoder(Map.this, Locale.getDefault());
try {
addresses=geocoder.getFromLocation(lattitude, longitude, 1);
Toast.makeText(Map.this, "Address:" + addresses.get(0).getAddressLine(0) + "City:"+ addresses.get(0).getAddressLine(1)+"Country:"+addresses.get(0).getAddressLine(2), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
private void getUserLocation(){
location_manager=(LocationManager) getSystemService(LOCATION_SERVICE);
if(location_manager!=null){
provider=location_manager.getBestProvider(criteria, true);
location=location_manager.getLastKnownLocation(provider);
location_manager.requestLocationUpdates(provider, Map.MIN_TIME_BW_UPDATES, Map.MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
lat=location.getLatitude();
lang=location.getLongitude();
}
}
#Override
public void onLocationChanged(Location location) {
google_map.clear();
drawMarker(lat, lang);
}
#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
}
}
Here is the snapshot that error i am getting in logcat.
I hope it will be helpful to solve error.
EDIT:-
If you don't want to monitor once again full code just try to view at getUserLocation method still the application stops working when i enable the GPS thanks for your support.
location is never initialized. Your are setting location as the variable that will hold the return value of getUserLocation() and it is also its parameter; both are null.
public class MainActivity extends MapActivity implements LocationListener {
private MapView mapView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Getting reference to MapView
mapView = (MapView) findViewById(R.id.map_view);
// Setting Zoom Controls on MapView
mapView.setBuiltInZoomControls(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
#Override
public void onLocationChanged(Location location) {
TextView tvLocation = (TextView) findViewById(R.id.tv_location);
// Getting latitude
double latitude = location.getLatitude();
// Getting longitude
double longitude = location.getLongitude();
// Setting latitude and longitude in the TextView tv_location
tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude );
// Creating an instance of GeoPoint corresponding to latitude and longitude
GeoPoint point = new GeoPoint((int)(latitude * 1E6), (int)(longitude*1E6));
// Getting MapController
MapController mapController = mapView.getController();
// Locating the Geographical point in the Map
mapController.animateTo(point);
// Applying a zoom
mapController.setZoom(15);
// Redraw the map
mapView.invalidate();
// Getting list of overlays available in the map
List<Overlay> mapOverlays = mapView.getOverlays();
// Creating a drawable object to represent the image of mark in the map
Drawable drawable = this.getResources().getDrawable(R.drawable.cur_position);
// Creating an instance of ItemizedOverlay to mark the current location in the map
CurrentLocationOverlay currentLocationOverlay = new CurrentLocationOverlay(drawable);
// Creating an item to represent a mark in the overlay
OverlayItem currentLocation = new OverlayItem(point, "Current Location", "Latitude : " + latitude + ", Longitude:" + longitude);
// Adding the mark to the overlay
currentLocationOverlay.addOverlay(currentLocation);
// Clear Existing overlays in the map
mapOverlays.clear();
// Adding new overlay to map overlay
mapOverlays.add(currentLocationOverlay);
}
#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
}
}
Download Here
I am trying to find my current location for an android project. When the application is loaded my current location is always null. I have set up the permissions in the manifest etc. When I find the current location I intend to use the coordinates to find distances to other locations on the map. My code snippet is below. Why do i always get a null value?
Here is my code:-
package com.example.location;
import android.content.Context;
import android.location.LocationManager;
import android.os.Bundle;
import android.location.Location;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import android.location.LocationListener;
import com.google.android.maps.MapController;
import android.widget.Toast;
import com.google.android.maps.GeoPoint;
public class MainActivity extends MapActivity implements LocationListener {
private MapView mapView;
private LocationManager locManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//fetch the map view from the layout
MapView mapView = (MapView) findViewById(R.id.mapview);
//make available zoom controls
mapView.setBuiltInZoomControls(true);
//latitude and longitude of Rome
double lat = 33.6667;
double lon = 73.1667;
//create geo point
GeoPoint point = new GeoPoint((int)(lat * 1E6), (int)(lon *1E6));
//get the MapController object
MapController controller = mapView.getController();
//animate to the desired point
controller.animateTo(point);
//set the map zoom to 13
// zoom 1 is top world view
controller.setZoom(13);
// invalidate the map in order to show changes
**mapView.invalidate();
// Use the location manager through GPS
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,
0, this);
//get the current location (last known location) from the location manager
Location location = locManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
Toast.makeText(
this,
"Current location:\nLatitude: " + location.getLatitude()
+ "\n" + "Longitude: " + location.getLongitude(),
Toast.LENGTH_LONG).show(); }
else {
Toast.makeText(this, "Cannot fetch current location!",
Toast.LENGTH_LONG).show();
}**
//when the current location is found – stop listening for updates (preserves battery)
locManager.removeUpdates(this);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
#Override
protected void onPause() {
super.onPause();
locManager.removeUpdates(this); //activity pauses => stop listening for updates
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
Look at this example. very good example for doing things like you want.
http://mobile.tutsplus.com/tutorials/android/android-sdk-build-a-mall-finder-app-points-of-interest/
I try to make a location app based on Android Maps API v2. I add marker for my location point and a GroundOverlay circle for location accuracy. But GroundOverlay setPosition function sets slightly different. I can't find why.
package com.example.locator;
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.GroundOverlay;
import com.google.android.gms.maps.model.GroundOverlayOptions;
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 android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.content.Context;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
public class MainActivity extends FragmentActivity implements LocationListener
{
GoogleMap mMap;
Location lastLocation = null;
private LocationManager locationManager;
private String provider;
Marker curLoc = null;
GroundOverlay curLocCircle = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(22.375675950685434, 29.83346939086914), 13));
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
} else {
//empty
}
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void onLocationChanged(Location location) {
if (location != null) {
if (null != curLoc) {
curLoc.remove();
}
if (null != curLocCircle) {
curLocCircle.remove();
}
LatLng loc = new LatLng(location.getLatitude(),location.getLongitude());
curLoc = mMap.addMarker(new MarkerOptions()
.position(loc)
.title("My location")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.location32)));
float accuracy = location.getAccuracy();
curLocCircle = mMap.addGroundOverlay(new GroundOverlayOptions()
.image(BitmapDescriptorFactory
.fromResource(R.drawable.location_circle))
.position(loc, accuracy)
.transparency(0)
);
curLocCircle.setPosition(loc);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(loc, 13));
}
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
When I pause app in debugger on line
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(loc, 13));
watches shows this data:
curLocCircle.getPosition() lat/lng: (22.397815012772206,29.954818561673164)
location.getLatitude() 22.397815
location.getLongitude() 29.9548184
loc lat/lng: (22.397815,29.9548184)
curLocCircle.getPosition() somehow shows incorrect location write after setPosition(loc);
Please help me with that.
The problem was in marker anchor.
Changed to:
curLoc = mMap.addMarker(new MarkerOptions()
.position(loc)
.anchor(0.5f, 0.5f)
.title("My location")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.location32)));
And everything is fine. I still don't get why location of GroundOverlay differs from defined location, but I don't care. It looks good.