SupportMapFragment with ViewPager: Cannot move camera or change map settings - android

I have a problem with the SupportMapFragment and moving the camera to a location on the map.
public class MapPositionFragment extends SupportMapFragment implements LocationListener{
private GoogleMap map = null;
private Button lockButton = null;
private Location currentLocation = null;
private LocationManager locationManager = null;
private View mapView = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mapView = super.onCreateView(inflater, container, savedInstanceState);
View v = inflater.inflate(R.layout.fragment_route_map, container, false);
SetUpMap(v);
return v;
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
if (isVisibleToUser){
SetUpLocationService();
}
}
private void SetUpLockButton(){
lockButton = (Button)getActivity().findViewById(R.id.lock_screen_button);
lockButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
ToggleLockButton();
}
});
}
private void ToggleLockButton(){
BaseSwipeActivity baseActivity = (BaseSwipeActivity)getActivity();
boolean swipeEnabled = baseActivity.TogglePaging();
if (swipeEnabled){
lockButton.setBackgroundResource(R.drawable.stock_lock_open);
}
else{
lockButton.setBackgroundResource(R.drawable.stock_lock);
}
}
private void SetUpLocationService(){
boolean gpsIsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean networkIsEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (networkIsEnabled){
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
} else if (gpsIsEnabled){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
}
private void SetCurrentLocation(final Location location){
if (map != null){
getActivity().runOnUiThread(new Runnable() {
public void run() {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 10);
map.moveCamera(cameraUpdate);
}
});
}
}
private void SetUpMap(View view) {
if (map == null){
getActivity().runOnUiThread(new Runnable() {
public void run() {
map = getMap();
map.getUiSettings().setMyLocationButtonEnabled(true);
map.setIndoorEnabled(true);
map.getUiSettings().setZoomControlsEnabled(false);
locationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
}
});
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
SetUpLockButton();
}
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
SetCurrentLocation(location);
}
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
It's SupportMapFragment which is positioned inside a ViewPager. The map is shown, but I cannot change the map settings and i'm not able to change the camera position. I thought maybe because it's in a other thread I have to use the UI Thread, but that doesn't change anything.
So maybe someone has an idea, it would be great!
thx Manuel

I encountered the same problem today. Here's my solution for it.
As you had:
// # SetUpMap()
map = getMap();
Replace it with:
// Remeber to change the map id (R.id.map) to what you have in the layout .xml
map = ((SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
Seems like this solution doesn't work with Android support library 21.0.x (I have tested for .2 and .3). As this method works with older Android support libraries there might be a bug etc.

Related

Why does creating a loop on my button make my android app hang?

I am writing an Android location based app. For my app i need to store my current location for every fixed time period. I create a button to start store those location using loop, but in device it hangs when start. If i remove the loop, it works. Whats the problem?
public class MainActivity extends FragmentActivity implements LocationListener {
GoogleMap googleMap;
Button btnStart,btnStop, btnstatus;
double fLat,fLon,sLat,sLon;
ArrayList<LatLng> locArray=new ArrayList<LatLng>();
int var,i;
double lat=0, lon=0;
LatLng fLL,sLL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStart=(Button) findViewById(R.id.btnStart);
btnStop=(Button) findViewById(R.id.btnStop);
btnstatus=(Button) findViewById(R.id.btnStatus);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(i=1;;i++)
{
Location loc=googleMap.getMyLocation();
double lat=loc.getLatitude();
double lon=loc.getLongitude();
LatLng latLon=new LatLng(lat, lon);
locArray.add(latLon);
}
}
});
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(i=1;i<locArray.size();i++)
{
LatLng src=locArray.get(i-1);
LatLng dest=locArray.get(i);
googleMap.addPolyline(new PolylineOptions().add(new LatLng(src.latitude, src.longitude),new LatLng(dest.latitude, dest.longitude)).width(3).color(Color.RED).geodesic(true));
}
}
});
SupportMapFragment supportMapFragment=(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
googleMap=supportMapFragment.getMap();
//googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
// googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
// googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);
googleMap.setMyLocationEnabled(true);
}
#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;
}
#Override
public void onLocationChanged(Location location) {
Location loc=googleMap.getMyLocation();
double latitude=loc.getLatitude();
double longitude=loc.getLongitude();
LatLng latLon=new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(latLon));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLon));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
#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
}
}
And here is my Button XML:
You have an endless for loop in the btnStart:
for (i = 1;; i++)
Why do you have a loop there? There is only one location anyway. Just remove the for loop and leave the internal code.
public void onClick(View v) {
Location loc = googleMap.getMyLocation();
double lat = loc.getLatitude();
double lon = loc.getLongitude();
LatLng latLon = new LatLng(lat, lon);
locArray.add(latLon);
}
your endless loop blocks UI thread will cause ANR :
for(i=1;;i++)
You can use single boolean variable to decide where to start and where to stop fetching the locations from providers
This is example, variable is isStartedFetching
private boolean isStartedFetching = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStart=(Button) findViewById(R.id.btnStart);
btnStop=(Button) findViewById(R.id.btnStop);
btnstatus=(Button) findViewById(R.id.btnStatus);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isStartedFetching = true;
/* for(i=1;;i++) // this is infinite loop, so application will hang
{
Location loc=googleMap.getMyLocation();
double lat=loc.getLatitude();
double lon=loc.getLongitude();
LatLng latLon=new LatLng(lat, lon);
locArray.add(latLon);
}
} */
});
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isStartedFetching = false;
for(i=1;i<locArray.size();i++)
{
LatLng src=locArray.get(i-1);
LatLng dest=locArray.get(i);
googleMap.addPolyline(new PolylineOptions().add(new LatLng(src.latitude, src.longitude),new LatLng(dest.latitude, dest.longitude)).width(3).color(Color.RED).geodesic(true));
}
}
});
SupportMapFragment supportMapFragment=(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
googleMap=supportMapFragment.getMap();
//googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
// googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
// googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);
googleMap.setMyLocationEnabled(true);
}
#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;
}
#Override
public void onLocationChanged(Location location) {
if(isStartedFetching) {
Location loc=googleMap.getMyLocation();
double latitude=loc.getLatitude();
double longitude=loc.getLongitude();
LatLng latLon=new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(latLon));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLon));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
}
You haven't set the condition for quitting the loop.
for (i = 1; ; i++)
for loop is
for (initialize to start loop; condition to stop loop; increment/decrement) {
// body of loop
}
just because you haven't put the condition when to stop,
that's why you are getting an error.

Not working plot multiple marker getOverlay().add(classobject) not accept

This is my code i want to plot multiple marker in google map
when i write mapview.getoverlay().add(overlaymarker) it is not working
i am not use MapActivity i use fragment so this is not supported getoverlays() please help me.......
fragmnt1.java
public class one extends Fragment implements LocationListener {
MapView mapView;
GoogleMap googleMap;
private boolean mapsSupported = true;
Location location;
double latitude; // latitude
double longitude;
LatLng latlang;
LocationManager manager;
Overlay_Marker overmarker;
frag provider;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final RelativeLayout parent = (RelativeLayout) inflater.inflate(R.layout.one, container, false);
mapView = (MapView) parent.findViewById(R.id.map);
provider=new frag(getActivity());
Log.d("spn", "oncreate view");
return parent;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
MapsInitializer.initialize(getActivity());
} catch (Exception ex) {
mapsSupported = false;
}
if (mapView != null) {
mapView.onCreate(savedInstanceState);
}
initializeMap();
Log.d("spn", "onactivity created");
}
private void initializeMap() {
if (googleMap == null && mapsSupported) {
mapView = (MapView) getActivity().findViewById(R.id.map);
googleMap = mapView.getMap();
Drawable dmarker=getResources().getDrawable(R.drawable.ic_launcher);
dmarker.setBounds(0, 0, dmarker.getIntrinsicWidth(), dmarker.getIntrinsicHeight());
overmarker=new Overlay_Marker(dmarker,getActivity());
Drawable windmill = getResources().getDrawable(R.drawable.ic_launcher);
Drawable bigBen = getResources().getDrawable(R.drawable.ic_launcher);
Drawable eiffelTower = getResources().getDrawable(R.drawable.ic_launcher);
overmarker.addOverlayItem(52372991, 4892655, "Amsterdam", windmill);
overmarker.addOverlayItem(51501851, -140623, "London", bigBen);
overmarker.addOverlayItem(48857522, 2294496, "Paris", eiffelTower);
//List<Overlay_Marker> temp = (List<Overlay_Marker>) mapView.getOverlay();
// temp.add(overmarker);
mapView.getOverlay().add(overmarker); /// Not working
GetLongitude_Latitude();
}
}
public void GetLongitude_Latitude()
{
manager=(LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
location=provider.getLocation(LocationManager.NETWORK_PROVIDER);
Criteria criteria = new Criteria();
// Getting the name of the provider that meets the criteria
String provider = manager.getBestProvider(criteria, false);
if(provider!=null && !provider.equals("")){
// Get the location from the given provider
Location location = manager.getLastKnownLocation(provider);
manager.requestLocationUpdates(provider, 20000, 1, this);
if(location!=null)
onLocationChanged(location);
// Toast.makeText(getActivity(), "Location retrieved"+location.getLatitude()+" and "+location.getLongitude(), Toast.LENGTH_SHORT).show();
//else
// Toast.makeText(getActivity(), "Location can't be retrieved", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getActivity(), "No Provider Found", Toast.LENGTH_SHORT).show();
}
Log.d("spn", "location"+location);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
#Override
public void onResume() {
super.onResume();
mapView.onResume();
initializeMap();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
public void onLocationChanged(Location location) {
latitude=location.getLatitude();
longitude=location.getLongitude();
latlang=new LatLng(latitude, longitude);
MarkerOptions marker=new MarkerOptions().position(latlang);
googleMap.addMarker(marker);
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setZoomGesturesEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
CameraPosition cameraPosition = new CameraPosition.Builder().target(
latlang).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
#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
}
}

Not getting location coordinates unless location has changed

Here is what I need to do. I need to launch my application and on the click of a button, I need to display the current coordinates, that is latitude and longitude. I followed this tutorial and used the following code for my purpose:
public class MainActivity extends Activity {
public double latitude;
public double longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
#Override
protected void onStart() {
super.onStart();
final TextView latValueLabel = (TextView)findViewById(R.id.latLabel);
final TextView lonValueLabel = (TextView)findViewById(R.id.lonLabel);
Button setButton = (Button)findViewById(R.id.set_button);
setButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
latValueLabel.setText(String.valueOf(latitude));
lonValueLabel.setText(String.valueOf(longitude));
}
});
}
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if(location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
#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
}
}
(Copy pasted only a part of the code, please ignore any unclosed brackets or anything like that.)
It continuously gets the latitude longitude as location changes and stores it to two double variables latitude and longitude and when the setButton is clicked, it displays the last stored lat-lon value. That would be the user's current location. Now the issue is, I launched the app and while still staying on the exact location from which the app is launched, I clicked the Set Button. But at that time the location is not changed, so the latitude and longitude are displayed as zero, which is the default value of the double variables. I need to take a walk around with the device so that the location is changed before I can get my actual coordinates. How can I get the lat-lon as soon as the app is launched?
You can use getLastKnownLocation(...) to initialise the longitude and latitude values like this:
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
This is your total class.
public class MainActivity extends Activity {
public double latitude;
public double longitude;
private TextView latValueLabel,lonValueLabel ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
#Override
protected void onStart() {
super.onStart();
latValueLabel = (TextView)findViewById(R.id.latLabel);
lonValueLabel = (TextView)findViewById(R.id.lonLabel);
Button setButton = (Button)findViewById(R.id.set_button);
setButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
latValueLabel.setText(String.valueOf(latitude));
lonValueLabel.setText(String.valueOf(longitude));
}
});
}
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if(location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
latValueLabel.setText(String.valueOf(latitude));
lonValueLabel.setText(String.valueOf(longitude));
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
}

current latitude & longitude in android fragment class

How can i get Current location.i have tried below code but getting null for location-
public class LocationsMapView extends Fragment implements LocationListener, android.location.LocationListener{
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
locationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,LocationsMapView.this);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
System.out.println("Location not available");
}
}
#Override
public void onLocationChanged(Location loc) {
current=new LatLng(loc.getLatitude(),loc.getLongitude());
lat=loc.getLatitude();longi=loc.getLongitude();
Toast.makeText(getActivity(), "location-"+loc.getLatitude(), Toast.LENGTH_SHORT).show();
System.out.println("location.."+lat+"..."+longi+" current .."+current);
}
#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
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
System.out.println("Location not available");
}
}
}
I have also given permission in manifest-
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Try on this way:
public static class XYZ extends Fragment
implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener,
LocationListener {
GoogleMap map;
LatLng latlng;
private LocationRequest lr;
private LocationClient lc;
MapFragment mapFragment;
ImageView iv;
private static View view;
public XYZ() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (view != null) {
ViewGroup parent = (ViewGroup) view.getParent();
if (parent != null)
parent.removeView(view);
}
try {
view = inflater.inflate(R.layout.XYZ, container,
false);
mapFragment = ((MapFragment) this.getActivity()
.getFragmentManager().findFragmentById(R.id.map));
iv = (ImageView) view.findViewById(R.id.iv);
map = mapFragment.getMap();
map.getUiSettings().setAllGesturesEnabled(false);
map.getUiSettings().setMyLocationButtonEnabled(false);
map.setMyLocationEnabled(true);
map.getUiSettings().setZoomControlsEnabled(false);
MapsInitializer.initialize(this.getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
Toast.makeText(getActivity(), "Google Play Services missing !",
Toast.LENGTH_LONG).show();
} catch (InflateException e) {
Toast.makeText(getActivity(), "Problems inflating the view !",
Toast.LENGTH_LONG).show();
} catch (NullPointerException e) {
Toast.makeText(getActivity(), "Google Play Services missing !",
Toast.LENGTH_LONG).show();
}
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lr = LocationRequest.create();
lr.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
lc = new LocationClient(this.getActivity().getApplicationContext(),
this, this);
lc.connect();
}
#Override
public void onLocationChanged(Location l2) {
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(
new LatLng(l2.getLatitude(), l2.getLongitude()), 15);
map.animateCamera(cameraUpdate);
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
}
#Override
public void onConnected(Bundle connectionHint) {
lc.requestLocationUpdates(lr, this);
}
#Override
public void onDisconnected() {
}
}
This is perfect working in my case.

Arcgis : how to get device location

Hie i tried to implement this codes in my application but it doesnt work , i dont know where i went wrong.
basically, when i launch the sample of the device location. it doesnt show me where is my current location and i dont see any blue dots that resembles the current location i am at.
the only thing that i see is the map . just a plain zoom out map.
I would be really thankful if someone who could help me out on how to get the current location with the blue dots that is displayed on the map..
this is my MainActivity.class
public class HelloWorld extends Activity {
MapView mMapView = null;
ArcGISTiledMapServiceLayer tileLayer;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Retrieve the map and initial extent from XML layout
mMapView = (MapView) findViewById(R.id.map);
mMapView.addLayer(new ArcGISTiledMapServiceLayer(
"http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer"));
mMapView.setOnStatusChangedListener(new OnStatusChangedListener() {
public void onStatusChanged(Object source, STATUS status) {
if (source == mMapView && status == STATUS.INITIALIZED) {
LocationService ls = mMapView.getLocationService();
ls.setAutoPan(false);
ls.start();
}
}
});
}
protected void onPause() {
super.onPause();
mMapView.pause();
}
#Override
protected void onResume() {
super.onResume();
mMapView.unpause();
}
}
this is a code that draws my location every 1 second via provider and GPS .
let's first declare variables :
private GraphicsLayer myGraphicalLayer;
MapView mMapView;
ArcGISLocalTiledLayer baseLayer;
private LocationManager mlocManager;
private LocationListener mlocListener;
in onCreate function WE CALL LocationListener:
mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, mlocListener);
mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, mlocListener);
// loading the map
mMapView = (MapView) findViewById(R.id.localMap);
baseLayer = new ArcGISLocalTiledLayer(basemapurl);
mMapView.addLayer(baseLayer);
// defining my position layer
myGraphicalLayer = new GraphicsLayer();
then a function to draw my location :
private void SetMyLocationPoint(final double x, final double y) {
PictureMarkerSymbol myPin = new PictureMarkerSymbol(getResources().getDrawable(
R.drawable.mylocation_icon));
Point wgspoint = new Point(x, y);
Point mapPoint = (Point) GeometryEngine.project(wgspoint, SpatialReference.create(4326),
mMapView.getSpatialReference());
Graphic myPinGraphic = new Graphic(mapPoint, myPin);
try {
myGraphicalLayer.removeAll();
} catch (Exception e) {
e.printStackTrace();
}
myGraphicalLayer.addGraphic(myPinGraphic);
myGraphicalLayer.setVisible(true);
mMapView.addLayer(myGraphicalLayer);
}
make internal class that implements MyLocationListener to get you instant location, and let it call the function named SetMyLocationPoint like this way :
public class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
SetMyLocationPoint(loc.getLongitude(), loc.getLatitude());
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "provider enabled", Toast.LENGTH_SHORT)
.show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "provider disabled", Toast.LENGTH_SHORT)
.show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
You need to use your own location manager or the location client to get the device's current location and then you will have to add that point on the map.
Your map should be in a MapFragment.
Get the googleMap object from the fragment and then add your custom blue dot on it.
LocationManager locationManager = (LocationManager) getApplicationContext()
.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
5000, 5, listener);
}
private LocationListener listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.e("Google", "Location Changed");
if (location == null)
return;
Log.e("latitude", location.getLatitude() + "");
Log.e("longitude", location.getLongitude() + "");
}
}
#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
}
};
The above code gets you the location in onLocationChanged method.
Note: i have used GPS_PROVIDER to get the location.
There are other ways to get the current location too.

Categories

Resources