moveCamera not updating to my current location on Google Maps Android? - android

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
}
}

Related

Current Location android

I've been following some tutorials and creating some simple android apps but I'm having some trouble with that one it only consists in showing the current location (longitude, latitude, altitude).
Any ideas about whats going on? Thanks in advance!
package com.ricard.location.app;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
TextView textLat;
TextView textLong;
TextView textAlt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textLat = (TextView) findViewById(R.id.textLat);
textLong = (TextView) findViewById(R.id.textLong);
textAlt = (TextView) findViewById(R.id.textAlt);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener ll = new mylocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}
class mylocationlistener implements LocationListener{
#Override
public void onLocationChanged(Location location){
if(location != null)
{
double plong = location.getLongitude();
double plat = location.getLatitude();
double palt = location.getAltitude();
textLat.setText(Double.toString(plat));
textLong.setText(Double.toString(plong));
textAlt.setText(Double.toString(palt));
}
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
}
There was an error with the reception of the signal on this device I tested it on a new one and it worked so it was a Hardware error thought.
Thanks!
private void moveToCurrentLocation() {
Criteria criteria = new Criteria();
LocationManager locationManager = (LocationManager) getContext().getSystemService(LOCATION_SERVICE);
String provider = locationManager.getBestProvider(criteria, true);
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = locationManager.getLastKnownLocation(provider);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLong latLong = new LatLong(latitude, longitude);
CameraPosition cameraPosition = new CameraPosition()
.target(latLong).zoom(whateverZoomThatYouWant);
map.animateCameraTo(cameraPosition);
}
// that is for fragment if you use it in activity delete --> getContext()

drop a marker in one place even if i move around

I have an onclick_Park() method that only drops a marker in a specific position (which is at my home's position) even if I move into another place and click the Park button it will drop a marker at my home's position and not my current location.
Any help with be appreciated.
Here is myMainActivity.java class
package com.example.carfinder;
import java.util.ArrayList;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
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.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
public class MainActivity extends android.support.v4.app.FragmentActivity implements LocationListener {
GoogleMap googleMap;
LatLng myPosition ;
LatLng parkingPosition;
GMapV2Direction md;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// if Google Play Services are available then
// 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();
googleMap.getUiSettings().setZoomControlsEnabled(false);
// 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);
if(location!=null){
// 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);
myPosition = new LatLng(latitude, longitude);
googleMap.moveCamera(CameraUpdateFactory.newLatLng(myPosition));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(16));
}
}
public void onClick_Clear(View v) {
// Removes all markers, overlays, and polylines from the map.
googleMap.clear();
}
public void onClick_Park(View v){
googleMap.addMarker(new MarkerOptions().position(myPosition).title("Parking Position"));
parkingPosition = myPosition;
}
public void onClick_getDirections(View v){
md = new GMapV2Direction();
googleMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
//org.w3c.dom.Document doc = md.getDocument(myPosition,parkingPosition,
// GMapV2Direction.MODE_DRIVING);
ArrayList<LatLng> directionPoint = md.getDirection(md.getDocument(myPosition,parkingPosition,
GMapV2Direction.MODE_DRIVING));
PolylineOptions rectLine = new PolylineOptions().width(3).color(
Color.RED);
for (int i = 0; i < directionPoint.size(); i++) {
rectLine.add(directionPoint.get(i));
}
Polyline polylin = googleMap.addPolyline(rectLine);
}
public void onClick_Traffic(View v){
}
#Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}
}
From your code, Location location = locationManager.getLastKnownLocation(provider); the location variable will fetch only the last known location stored by the app and not the present location.
Solution: Call the function to mark inside the
public void onLocationChanged(Location arg0) {}
so that it checks your location every time when it is changed.
UPDATE : Refer this link.
http://wptrafficanalyzer.in/blog/showing-current-location-using-onmylocationchangelistener-in-google-map-android-api-v2/

Google Maps Android Api V2 Driving Route Isn't Working

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

Android: can't get current location on maps

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

Android GroundOverlay sets incorrect position

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.

Categories

Resources