How to get Circle Bounds on Google Maps V2 - android

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();
}

Related

Google maps adding a new marker every update

been trying for a while to sort my maps problem, which is the marker. every time the map updates it adds a new marker. this leaves several markers on the same location.
I want to get this sorted before adding other content like directions.
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
return;//
}
mMap.setMyLocationEnabled(true); // shows location on map
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
listener = new LocationUpdateListener();
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
}
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
MarkerOptions options = new MarkerOptions() // This adds in a marker
.position(latLng)
.title("Reverse Geo Toast here ???"); // when marker clicked, it will display you are here
mMap.addMarker(options);
// mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
float zoomLevel = (float) 10; //This zooms into the marker
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoomLevel));
}
You can update the position of an existing marker using setPosition (Reference):
private Marker marker;
// ...
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
if (marker == null) {
MarkerOptions options = new MarkerOptions() // This adds in a marker
.position(latLng)
.title("Reverse Geo Toast here ???"); // when marker clicked, it will display you are here
marker = mMap.addMarker(options);
}
else {
marker.setPosition(latLng);
}
// mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
float zoomLevel = (float) 10; //This zooms into the marker
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoomLevel));
}

Can't resolve mLatLng in Center of the circle

In my Android Map I simply draw a circle and I need the current location to be the center of the circle and when change the location of the device, the circle must be rechanged and load markers again inside the circle.
Here is my code.
First I simply hard coded some 5 places.
LatLng POINTA = new LatLng(6.9192, 79.8950);
LatLng POINTB = new LatLng(6.9006, 79.8533);
LatLng POINTC = new LatLng(6.9147, 79.8778);
LatLng POINTD = new LatLng(6.9036, 79.9547);
LatLng POINTE = new LatLng(6.8397, 79.8758);
Then here is the place I draw the circle and load markers.
public static boolean isMyLocationSet = false; // Get Current location ass default location
#Override
public void onMyLocationChange(Location location) {
isMyLocationSet=false; // Get Current location ass default location
Location target = new Location("target");
for(LatLng point : new LatLng[]{POINTA,POINTB,POINTC,POINTD,POINTE}){
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationChangeListener(this);
LocationManager mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = mLocationManager.getBestProvider(criteria, true);
Location currentLocation = mLocationManager.getLastKnownLocation(provider);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng mLatLng = new LatLng(latitude, longitude);
Circle circle = mMap.addCircle(new CircleOptions()
.center(new LatLng(mLatLng))
.radius(10000)
.strokeColor(Color.BLUE)
.strokeWidth(2));
target.setLatitude(point.latitude);
target.setLongitude(point.longitude);
Marker marker = mMap.addMarker(new MarkerOptions()
.position(new LatLng(point.latitude, point.longitude))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
float[] distance = new float[2];
if(location.distanceTo(target) < 10000) {
marker.setVisible(true);
}
else {
marker.remove();
}
}
}
Here I cannot resolve mLatLng in center(new LatLng(mLatLng)) It says
Latlng(double, double) in Latlng cannot be applied to (com.google.andrdoid.gms.maps.model.Latlng)
What should I do for this and Is there anything I did wrong with the code?
you put LatLng object in create new LatLng class object
so given this type of message.Pls use only object as parameter
like
LatLng mLatLng = new LatLng(latitude, longitude);
Circle circle = mMap.addCircle(new CircleOptions()
.center(mLatLng)
.radius(10000)
.strokeColor(Color.BLUE)
.strokeWidth(2));
OR
Circle circle = mMap.addCircle(new CircleOptions()
.center(new LatLng(latitude, longitude))
.radius(10000)
.strokeColor(Color.BLUE)
.strokeWidth(2));

How to Redirect my current Location in google Maps

how can I redirect my current Location when I open the Google Map
here is my code in SetUpMap()
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
mMap.setMyLocationEnabled(true);
And also how can I change the Marker ? I only get that blue circle in my location. I want to change it to a Pin
If you want to open map with your location through any activity then use this code
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps?saddr=20.344,34.34&daddr=20.5666,45.345"));
startActivity(intent);
If you are using Google map then using location find lat long and pass this lat long in maps object
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);
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));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
locationTv.setText("Latitude:" + latitude + ", Longitude:" + longitude);
}
Get the current location of the user as soon as your Map is ready and you need to animate the camera like this
Location location = this.mGoogleMap.getMyLocation();
if (location != null) {
LatLng target = new LatLng(location.getLatitude(), location.getLongitude());
CameraPosition position = this.mGoogleMap.getCameraPosition();
Builder builder = new CameraPosition.Builder();
builder.zoom(15);
builder.target(target);
this.mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(builder.build()));
}
So, getMyLocation() has to fetch the location of the user. Use can use PROVIDERS to fetch the location. You can also listen to location using LocationListener using GoogleApiClient. Kindly read the documentation of Getting the Last Known Location and Receiving Location Updates before posting here.
To give the custom marker for your location there is something called addMarker
mGoogleMap.addMarker(new MarkerOptions()
.position(new LatLng(location.getLatitude(), location.getLogitude()))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
You can try with this code, We can get our location in google map by NETWORK_PROVIDER. NETWORK_PROVIDER pick your location from your WIFI location or your network provider companies like(IDEA,AIRTEL,VODAPHONE) .
try {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager()
.findFragmentById(R.id.map)).getMap();
}
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMyLocationEnabled(true);
LocationManager location_manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener listner = new getlatlngListner();
location_manager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 2000, 2000, listner);
location_manager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
} catch (Exception e) {
e.printStackTrace();
}
private MarkerOptions mMarkerOptions = new MarkerOptions();
mMarkerOptions.visible(true);
mMarkerOptions.icon(BitmapDescriptorFactory.fromBitmap(Your bitmap));
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
LatLng mPos = new LatLng(location.getLatitude(),location.getLongitude());
mMarkerOptions.position(mPos);
mMap.addMarker(mMarkerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(mPos));
mMap.animateCamera(CameraUpdateFactory.zoomTo(17));
}
});

ensure location accuracy and track user on Google map

My android application function is to track the user location when it walk/run or when he never moves(then location should not change)First, the location is inaccurate and red marker keeps popping out on the map even if i never move. the position where it pops out is also inaccurate.
For those who did similar location tracking app before, the blue dot should be the same place as the latest red marker right? but my blue dot is always away most of the time. red marker shows a more accurate position(although still inaccurate)
i have tested it in my house, outside, in a vehicle. when it is in my house, sometimes location keeps changing, sometimes location never change. i cannot predict it. usually gps don't work well in-house so i leave it first
when i test it outside, sometimes it is better but it is still inaccurate. when i never move/move or move slow it update on the wrong location. althought it is sometimes little better then in roof. but in the end it is still unuseable.
when i test it in the car, it is better as it won't pop out so much location should be more accurate blue dot and red marker are sometimes together. although there are still inaccurate sometimes. but it does not matter as my app is supposed to use when the user is walking/running not in a moving vehicle.
for all three, red marker appears(no matter how frequently) around the correct environment(house, road, certain building) sometimes, but the blue dot is not, most of the times it is wrong. but i wanted the blue dot as a tracker for the user. user would not know which red marker is his current location even if it is accurate. the title "you are here" could appear on any marker when i tap on it, where it is new or old. so it is not effective. and when a new one appear, the title does not appear by itself.
the problem i am trying to solve is to ensure location accuracy, even if not good or perfect at lease be useable, and have the blue dot track the user continuously,or red marker as long as sometimes tell the where is he accurately(title only appears on the latest marker by itself).
i am research for a long time and i do not know what else i can implement to make it more accurate. the distance calculation i believe should be accurate but it depends on the location so it will becomes inaccurate too. sorry for the large text i just thought i should explain myself clearer...
public class MainActivity extends FragmentActivity implements LocationListener{
protected LocationManager locationManager;
private GoogleMap googleMap;
Button btnStartMove,btnPause,btnResume,btnStop;
static double n=0;
Long s1,r1;
double dis=0.0;
Thread t1;
EditText userNumberInput;
boolean bool=false;
int count=0;
double speed = 1.6;
double lat1,lon1,lat2,lon2,lat3,lon3,lat4,lon4;
double dist = 0.0;
double time = 0.0;
double velocity = 0.0;
TextView distance;
Button btnDuration;
float[] result;
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES =1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 4000; //in milliseconds
boolean startDistance = false;
boolean startButtonClicked = false;
MyCount counter;
int timer = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MINIMUM_TIME_BETWEEN_UPDATES,MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, this);
if(isGooglePlay())
{
setUpMapIfNeeded();
}
distance=(TextView)findViewById(R.id.Distance);
btnDuration=(Button)findViewById(R.id.Duration);
btnStartMove=(Button)findViewById(R.id.Start);//start moving
btnStop=(Button)findViewById(R.id.Stop);
//prepare distance...........
Log.d("GPS Enabled", "GPS Enabled");
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String provider = locationManager.getBestProvider(criteria, true);
Location location=locationManager.getLastKnownLocation(provider);
btnStartMove.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
Log.d("GPS Enabled", "GPS Enabled");
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String provider = locationManager.getBestProvider(criteria, true);
Location location=locationManager.getLastKnownLocation(provider);
lat3 = location.getLatitude();
lon3 = location.getLongitude();
startButtonClicked=true;
startDistance=true;
counter= new MyCount(30000,1000);
counter.start();
btnStartMove.setText("Started...");
}
});
btnStop.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
startButtonClicked=false;
startDistance=false;
//Double.valueOf(distance.getText().toString()
Double value=dist;
Double durationValue=time;
Double speedValue=velocity;
Intent intent = new Intent(MainActivity.this, FinishActivity.class);
intent.putExtra("dist", value);
intent.putExtra("time",durationValue);
intent.putExtra("velocity",speedValue);
startActivity(intent);
counter.cancel();
n=0;
r1=null;
time=0.0;
btnStartMove.setText("Start Move");
finish();
}
});
btnDuration.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
if(startButtonClicked=true)
{
time=n*30+r1;
velocity=dist/time;
DecimalFormat df = new DecimalFormat("#.##");
Toast.makeText(MainActivity.this,"Duration :"+String.valueOf(time) + "Speed :"+String.valueOf(df.format(velocity)),Toast.LENGTH_LONG).show();
}
}
});
if(location!= null)
{
//Display current location in Toast
String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(MainActivity.this, message,
Toast.LENGTH_LONG).show();
}
else if(location == null)
{
Toast.makeText(MainActivity.this,
"Location is null",
Toast.LENGTH_LONG).show();
}
}
private void setUpMapIfNeeded() {
if(googleMap == null)
{
googleMap =((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.displayMap)).getMap();
if(googleMap != null)
{
setUpMap();
}
}
}
private void setUpMap()
{
//Enable MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
//Get locationManager object from System Service LOCATION_SERVICE
//LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
//Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
//Get the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
if(provider == null)
{
onProviderDisabled(provider);
}
//set map type
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//Get current location
Location myLocation = locationManager.getLastKnownLocation(provider);
if(myLocation != null)
{
double latitude = myLocation.getLatitude();
//Get longitude of the current location
double longitude = myLocation.getLongitude();
//Create a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
//Show the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(20));
googleMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).snippet("You are here!").title("You are here!"));
}
locationManager.requestLocationUpdates(provider, 0, 0, this);
}
private boolean isGooglePlay()
{
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (status == ConnectionResult.SUCCESS)
{
Toast.makeText(MainActivity.this, "Google Play Services is available",
Toast.LENGTH_LONG).show();
return(true);
}
else
{
GooglePlayServicesUtil.getErrorDialog(status, this, 10).show();
}
return (false);
}
#Override
public void onLocationChanged(Location myLocation) {
System.out.println("speed " + myLocation.getSpeed());
//show location on map.................
//Get latitude of the current location
double latitude = myLocation.getLatitude();
//Get longitude of the current location
double longitude = myLocation.getLongitude();
//Create a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
//Show the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(20));
googleMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).snippet("You are here!").title("You are here!"));
//show distance............................
if(startDistance == true)
{
Toast.makeText(MainActivity.this,
"Location has changed",
Toast.LENGTH_LONG).show();
if(myLocation != null)
{
//latitude.setText("Current Latitude: " + String.valueOf(loc2.getLatitude()));
//longitude.setText("Current Longitude: " + String.valueOf(loc2.getLongitude()));
float[] results = new float[1];
Location.distanceBetween(lat3, lon3, myLocation.getLatitude(), myLocation.getLongitude(), results);
System.out.println("Distance is: " + results[0]);
dist += results[0];
DecimalFormat df = new DecimalFormat("#.##"); // adjust this as appropriate
if(count==1)
{
distance.setText(df.format(dist) + "meters");
}
lat3=myLocation.getLatitude();
lon3=myLocation.getLongitude();
count=1;
}
}
if(startButtonClicked == true)
{
startDistance=true;
}
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(MainActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(MainActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(MainActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MINIMUM_TIME_BETWEEN_UPDATES,MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, this);
}
public class MyCount extends CountDownTimer{
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
counter= new MyCount(30000,1000);
counter.start();
n=n+1;
}
#Override
public void onTick(long millisUntilFinished) {
s1=millisUntilFinished;
r1=(30000-s1)/1000;
}
}}

android locationListener not working?

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.

Categories

Resources