Friday 18 November 2011

Android location based services to show current location of the device with pin point

Hi here i am providing the code snippet for showing the current location of the android mobile. Here in my java code i used the Location manager class to get the location lat, lan values. Using location listener class we can get locations with good performance.
Here i used Location listener as GPS_PROVIDE but better to use both GPS_PROVIDER and NETWORK_PROVIDER also why because some times mobile can not get the location points using GPS.
Here i registered location listener in onResume() method and released the listener in onPause() method.
I displayed the location values as a text view and displayed the map for the respected location with pointed image. To show the point image i used  MapItemOverlay class object which is the sub class for the ItemizedOverlay. I passed the geopoint and address for the MapItemOverlay class object. Then it will display the location pointed by the drawable image.

Here is my java code:

LocationActivity.java




import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class LocationActivity extends MapActivity implements LocationListener {

private static final String TAG = "LocationActivity";

LocationManager locationManager;
Geocoder geocoder;
GeoPoint p ;
TextView locationText;
MapView map;
MapController mapController;
String addr;
int rlat,rlng;
List<Overlay> listOfOverlays;
Drawable drawable;
 List<GeoPoint> pointsList ;
 List<String> addressarray;
 MapItemOverlay itemizedoverlay ;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        pointsList=new ArrayList<GeoPoint>();
        addressarray=new ArrayList<String>();
        locationText = (TextView)this.findViewById(R.id.lblLocationInfo);
        map = (MapView)this.findViewById(R.id.mapview);
        map.setBuiltInZoomControls(true);
        mapController = map.getController();
        mapController.setZoom(16);
        locationManager = (LocationManager)this.getSystemService(LOCATION_SERVICE);
        geocoder = new Geocoder(this);
        Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (location != null) {
        Log.v(TAG, location.toString());
final int lat = (int) (location.getLatitude() * 1E6);
final int lng = (int) (location.getLongitude() * 1E6);
this.onLocationChanged(location);        
        }
    }

    @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, 1000, 10, this);
}
   
@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}

@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.d(TAG, "onLocationChanged with location " + location.toString());
// Displays lat, long, altitude and bearing
String text = String.format("Lat:\t %f\nLong:\t %f\nAlt:\t %f\nBearing:\t %f", location.getLatitude(), location.getLongitude(), location.getAltitude(), location.getBearing());
this.locationText.setText(text);

try {
// This gets a list of addresses
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 10);
for (Address address : addresses) {
this.locationText.append("\n" + address.getAddressLine(0));
addr+=address.getAddressLine(0);
}

rlat = (int)(location.getLatitude() * 1000000);
rlng = (int)(location.getLongitude() * 1000000);
addressarray.add(addr);


GeoPoint point = new GeoPoint(rlat,rlng);
pointsList.add(point);
mapController.animateTo(point);
 int minLat = Integer.MAX_VALUE;
int minLong = Integer.MAX_VALUE;
int maxLat = Integer.MIN_VALUE;
int maxLong = Integer.MIN_VALUE;
for (int i=0;i<pointsList.size();i++) {
/*maxLat=maxLat+point.getLatitudeE6();
maxLong=maxLong+point.getLongitudeE6();*/
minLat = Math.min(pointsList.get(i).getLatitudeE6(), minLat);
minLong = Math.min(pointsList.get(i).getLongitudeE6(), minLong);
maxLat = Math.max(pointsList.get(i).getLatitudeE6(), maxLat);
maxLong = Math.max(pointsList.get(i).getLongitudeE6(), maxLong);
}
maxLat = maxLat + (int)((maxLat-minLat)*0.1);
minLat = minLat - (int)((maxLat-minLat)*0.1);
maxLong = maxLong + (int)((maxLong-minLong)*0.2);
minLong = minLong - (int)((maxLong-minLong)*0.2);
mapController.zoomToSpan(Math.abs(minLat - maxLat), Math.abs(minLong - maxLong));
mapController.animateTo(new GeoPoint((maxLat + minLat) / 2,(maxLong + minLong) / 2));
listOfOverlays = map.getOverlays();
listOfOverlays.clear();
drawable = this.getResources().getDrawable(R.drawable.icon);
itemizedoverlay = new MapItemOverlay(drawable,this);
for(int i=0;i<pointsList.size();i++){
        p=pointsList.get(i);
    OverlayItem overlayitem = new OverlayItem(p, "location",addressarray.get(i));
        itemizedoverlay.addOverlay(overlayitem);
       }
       itemizedoverlay.nowPopulate();
       listOfOverlays.add(itemizedoverlay);

} catch (IOException e) {
Log.e("LocateMe", "Could not get Geocoder data", e);
}
}

@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

}
public class MapItemOverlay extends ItemizedOverlay {
    private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
    Context mContext;
    String id1;
    Float mLat = null ;
    Float mLong = null ;
    Location myLocation = null ;
    LocationManager lm = null ;
    //String[] id,title,spotlight,addr,distance,addr2,phone,url,graphic,city,statecode,zipcode,myLat,myLong,partHead;
    public MapItemOverlay(Drawable defaultMarker,Context context) {
    super(boundCenterBottom(defaultMarker));
    mContext = context;
    // TODO Auto-generated constructor stub
    }
    public void addOverlay(OverlayItem overlay) {
    mOverlays.add(overlay);
   
    }
    public void nowPopulate(){
    populate();
    }
    @Override
    protected OverlayItem createItem(int i) {
    // TODO Auto-generated method stub
    return mOverlays.get(i);

    }
    @Override
    public int size() {
    // TODO Auto-generated method stub
    return mOverlays.size();
    }
    @Override
    protected boolean onTap(final int index) {
    final OverlayItem item = mOverlays.get(index);
    return true;
    }
}
}

Please include package for the above code.
code for
main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Waiting for location..."
    android:id="@+id/lblLocationInfo"
/>
<com.google.android.maps.MapView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mapview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:clickable="true"
    android:apiKey="0D8OQwybgC6JZo8d3VmMRNL40NgE8-aghGarxeQ"
/>
</LinearLayout>
You must generate your own map api key to replace the andoid:apiKey="XXXX" values. then only you can see the map in your emulator/ device

And you must add these permissions into your manifest.xml file


    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
the above tags are add outside the <application> tag and the below tag must add inside the <application> tag
<uses-library android:name="com.google.android.maps" />


The output may like this screenshot




Thank you.



No comments:

Post a Comment