some issue in detecting location application crashes - android

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

Related

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

Cannot fetch Location using google maps

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/

geolocalisation with android

i am trying to make my emulator indicate where i am on the map , the problem is i don't get my real location nor the compass
i am only using the emulator on the computer
i integered the google map,the key, the imports inthe manifest.xml
here is the code :
package com.training.surveyproject;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.Toast;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
public class SurveyActivity extends MapActivity implements LocationListener
{
private MapView mapView = null;
private LocationManager lm = null;
private double lat = 0;
private double lng = 0;
private MapController mc = null;
private MyLocationOverlay myLocation = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_survey);
mapView = (MapView) this.findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
lm = (LocationManager) this.getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, this);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 0, this);
mc = mapView.getController();
mc.setZoom(12);
myLocation = new MyLocationOverlay(getApplicationContext(),mapView);
myLocation.runOnFirstFix(new Runnable(){
public void run(){
mc.animateTo(myLocation.getMyLocation());
mc.setZoom(17);
}
});
mapView.getOverlays().add(myLocation);
myLocation.enableMyLocation();
myLocation.enableCompass();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_S)
{
mapView.setSatellite(!mapView.isSatellite());
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onLocationChanged(Location location)
{
lat = location.getLatitude();
lng = location.getLongitude();
Toast.makeText(getBaseContext(),
"Location change to : Latitude = " + lat + " Longitude = " + lng,
Toast.LENGTH_SHORT).show();
GeoPoint p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
mc.animateTo(p);
mc.setCenter(p);
}
#Override
protected boolean isRouteDisplayed()
{
return false;
}
#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
}
}
thank u
You can send simulated GPS fixes to an emulator by opening the DDMS perspective and the 'emulator control' tab in there. That tab has a 'location control' option which will send the lat/long to the emulator.

Gps Notification Icon Not Blinking

i am trying google maps api on my android phone via following code. My app locating my phone and working great but gps notification icon not blinking. How can i blink gps icon when locating my phone.
Thanks For Replies.
Manifest:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
And The Code :
import java.util.List;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.provider.Settings;
import android.widget.EditText;
import android.widget.Toast;
public class main extends MapActivity {
MapController mControl;
GeoPoint geoP;
MapView mapV;
MyLocationOverlay compass;
EditText etext;
String provider;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
etext = (EditText) findViewById(R.id.latLong);
mapV = (MapView) findViewById(R.id.mapView);
mapV.displayZoomControls(true);
mapV.setBuiltInZoomControls(true);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
boolean enable = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enable) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
Criteria criteria = new Criteria();
//criteria.setAccuracy(Criteria.ACCURACY_FINE);
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
Double lat = location.getLatitude() * 1E6;
Double longi = location.getLongitude() * 1E6;
geoP = new GeoPoint(lat.intValue(), longi.intValue());
List<Overlay> mapOverlays = mapV.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.androidmarker);
compass = new MyLocationOverlay(this, mapV);
HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable, this);
OverlayItem overlayitem = new OverlayItem(geoP, "Hola, Mundo!","I'm in Mexico City!");
itemizedoverlay.addOverlay(overlayitem);
mapV.getOverlays().add(compass);
mapOverlays.add(itemizedoverlay);
mControl = mapV.getController();
mControl.animateTo(geoP);
mControl.setZoom(5);
mControl.setCenter(geoP);
locationManager.requestLocationUpdates(provider, 0, 0,
new LocationListener() {
public void onStatusChanged(String provider, int status,
Bundle extras) {
if (status == LocationProvider.AVAILABLE) {
Toast.makeText(getApplicationContext(),
"LocationProvider.AVAILABLE",
Toast.LENGTH_SHORT).show();
} else if (status == LocationProvider.TEMPORARILY_UNAVAILABLE) {
Toast.makeText(getApplicationContext(),
"LocationProvider.TEMPORARILY_UNAVAILABLE",
Toast.LENGTH_SHORT).show();
} else if (status == LocationProvider.OUT_OF_SERVICE) {
Toast.makeText(getApplicationContext(),
"LocationProvider.OUT_OF_SERVICE",
Toast.LENGTH_SHORT).show();
}
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
public void onLocationChanged(Location location) {
Toast.makeText(getApplicationContext(),
"Location Changed", Toast.LENGTH_SHORT).show();
}
});
//etext.setText(String.valueOf(lat) + "," + String.valueOf(longi));
}
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
compass.disableCompass();
}
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
compass.enableCompass();
}
protected boolean isRouteDisplayed() {
return false;
}
t0mm13b, working on my handset but GPS notification icon not blinking. Virtual Device means Emulator. I solved problem.
Code :
package com.yunusoksuz.gmapstest;
import android.app.Activity;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class YnsmapsActivity extends Activity implements LocationListener {
/** Called when the activity is first created. */
private LocationManager locationManager;
private Location location;
private String provider;
private Double lat, longi;
private Criteria criteria;
TextView tv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.tv1);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
provider = locationManager.getBestProvider(criteria, false);
location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 0, 0, this);
}
public void onLocationChanged(Location location) {
Toast.makeText(
this,
"Lat : " + location.getLatitude() + " LONG : "
+ location.getLongitude(), Toast.LENGTH_SHORT).show();
tv.setText("Lat : " + location.getLatitude() + " LONG : "
+ location.getLongitude());
}
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
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
locationManager.removeUpdates(this);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, this);
}
}
Now gps notification blinking.

Map location returning null for android

My getLastKnownLocation is turning up "null". I can get the locations I put in to show however get the users location has been trying. From the docs, here, and 4 05 tutorials I thought I was doing it right, but...... I'm not. I just cannot seem to figure out why.
If someone has a sec to look this over that would be great.
package com.kita.Maps;
import java.util.ArrayList;
import java.util.List;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.MailTo;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.Toast;
public class MapsActivity extends MapActivity implements LocationListener{
/** Called when the activity is first created. */
MapView map;
private MyLocationOverlay me = null;
Drawable d;
List<Overlay> overlayList;
LocationManager lm;
String towers;
int lat;
int longi;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
map = (MapView) findViewById(R.id.myMain);
map.setBuiltInZoomControls(true);
Touchy t = new Touchy();
overlayList = map.getOverlays();
overlayList.add(t);
map.getController().setCenter(
getPoint(40.76793169992044, -73.98180484771729));
map.getController().setZoom(17);
map.setBuiltInZoomControls(true);
Drawable marker = getResources().getDrawable(R.drawable.pin_yellow);
marker.setBounds(0, 0, marker.getIntrinsicWidth(),
marker.getIntrinsicHeight());
map.getOverlays().add(new SitesOverlay(marker));
me = new MyLocationOverlay(this, map);
map.getOverlays().add(me);
d = getResources().getDrawable(R.drawable.pin_blue);
// Geo Location of phone
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
towers = lm.getBestProvider(crit, false);
Location location = lm.getLastKnownLocation(towers);
if(location != null){
lat = (int) (location.getLatitude()*1E6);
longi = (int) (location.getLongitude()*1E6);
GeoPoint ourLocation = new GeoPoint(lat, longi);
OverlayItem overlayItem = new OverlayItem(ourLocation, "Quit hitting your self","");
CustomPinpoint custom = new CustomPinpoint(d, MapsActivity.this);
custom.insertPinpoint(overlayItem);
overlayList.add(custom);
}
else{
Toast.makeText(MapsActivity.this, "Couldn't get provider", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onResume() {
super.onResume();
me.enableCompass();
lm.requestLocationUpdates(towers, 500, 1, this);
}
#Override
public void onPause() {
super.onPause();
me.disableCompass();
lm.removeUpdates(this);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
class Touchy extends Overlay {
public boolean onTouchEvent(MotionEvent e, MapView m) {
return false;
}
}
private GeoPoint getPoint(double lat, double lon) {
return (new GeoPoint((int) (lat * 1000000.0), (int) (lon * 1000000.0)));
}
private class SitesOverlay extends ItemizedOverlay<OverlayItem> {
private List<OverlayItem> items = new ArrayList<OverlayItem>();
public SitesOverlay(Drawable marker) {
super(marker);
boundCenterBottom(marker);
items.add(new OverlayItem(getPoint(40.748963847316034,
-73.96807193756104), "UN", "United Nations"));
items.add(new OverlayItem(getPoint(40.76866299974387,
-73.98268461227417), "Lincoln Center",
"Home of Jazz at Lincoln Center"));
items.add(new OverlayItem(getPoint(40.765136435316755,
-73.97989511489868), "Carnegie Hall",
"Where you go with practice, practice, practice"));
items.add(new OverlayItem(getPoint(40.70686417491799,
-74.01572942733765), "The Downtown Club",
"Original home of the Heisman Trophy"));
populate();
}
#Override
protected OverlayItem createItem(int i) {
return (items.get(i));
}
#Override
protected boolean onTap(int i) {
Toast.makeText(MapsActivity.this, items.get(i).getSnippet(),
Toast.LENGTH_SHORT).show();
return (true);
}
#Override
public int size() {
return (items.size());
}
}
public void onLocationChanged(Location l) {
// TODO Auto-generated method stub
lat = (int) (l.getLatitude() *1E6);
longi = (int) (l.getLongitude()*1E6);
GeoPoint ourLocation = new GeoPoint(lat, longi);
OverlayItem overlayItem = new OverlayItem(ourLocation, "Quit hitting your self","");
CustomPinpoint custom = new CustomPinpoint(d, MapsActivity.this);
custom.insertPinpoint(overlayItem);
overlayList.add(custom);
}
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
}
}
Here is my custom pointer class:
package com.kita.Maps;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.drawable.Drawable;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;
public class CustomPinpoint extends ItemizedOverlay<OverlayItem>{
private ArrayList<OverlayItem> pinpoints = new ArrayList<OverlayItem>();
private Context c;
public CustomPinpoint(Drawable defaultMarker) {
super(boundCenter(defaultMarker));
// TODO Auto-generated constructor stub
}
public CustomPinpoint(Drawable m, Context context) {
// TODO Auto-generated constructor stub
this(m);
c = context;
}
#Override
protected OverlayItem createItem(int i) {
// TODO Auto-generated method stub
return pinpoints.get(i);
}
#Override
public int size() {
// TODO Auto-generated method stub
return pinpoints.size();
}
public void insertPinpoint(OverlayItem item){
pinpoints.add(item);
this.populate();
}
}
Instead of getLastKnownLocation, try requestLocationUpdates. You can use a LocationListener to listen for location updates. More info: https://developer.android.com/reference/android/location/LocationListener.html
getLastKnownLocation gives nulls, a lot, it's just the nature of the beast.
Use a LocationListener and wait if you want to secure a solid position. getLastKnownLocation is really only good for priming location based logic being feed by a LocationListener.
Generally speaking whats going on is if you request a location for a detector (like GPS) and it has never gotten a location since its last boot up, it will return null. This is why it is usually better to request the updates first, which will cause the device to actively find one.
One technique is to find the location BEFORE you need it, then use getLastKnownLocation when you actually need it.
When using getLastKnownLocation it is always best to a) do your best to ensure that the location tracking device your using has already found a location as some point during this boot, and b) you check for nulls just in case.
As a side note, I would recommend checking the accuracy when getting new locations. It is very common that the first location found is not that as accurate as it could be, at the same time if you look for a period of time the LAST location found may not be as accurate as some other location found during the cycle. The key is use the GPS as little and as well controlled as possible, and double check your results.

Categories

Resources