1.First step to import PLAYSERVICE file from sdk/extras/google/lib/google_play_lib project
2.Create new Android Project then select new project and right click select PROPERTIES
then ANDROID and add imported lib project to this new created project finally click OK button.
3.Create GOOGLE API CONSOLE account and create new project and create new API KEY for google map project
4.Eclipse ->Window->android->build then copy the SHA1 key and add your
package name then generate api key
then do it following
MainActivity.java
package com.exmaps;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.Marker;
public class MainActivity extends FragmentActivity {
public static GoogleMap mGoogleMap;
public static Marker mark;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}else { // Google Play Services are available
// Getting reference to the SupportMapFragment
SupportMapFragment fragment = ( SupportMapFragment) getSupportFragmentManager().
findFragmentById(R.id.map);
// Getting Google Map
mGoogleMap = fragment.getMap();
// Enabling MyLocation in Google Map
mGoogleMap.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 boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.Start) {
startService(new Intent(this, GPSSERVICE.class));
return true;
}
if (id == R.id.Exit) {
stopService(new Intent(this, GPSSERVICE.class));
finish();
return true;
}
if (id == R.id.Satilite) {
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
return true;
}
if (id == R.id.Terrain) {
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
return true;
}
return super.onOptionsItemSelected(item);
}
}
GPSSERVICE.java
package com.exmaps;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
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.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.Circle;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import static com.exmaps.MainActivity.*;
public class GPSSERVICE extends Service
{
public static final String BROADCAST_ACTION = "Hello World";
private static final int TWO_MINUTES = 1000 * 60 * 2;
public LocationManager locationManager;
public MyLocationListener listener;
public Location previousBestLocation = null;
public static String local,sub;
public static String route_id;
public static String periorty;
public static long distanceInMeters;
Circle myCircle;
// public static double dblatitude,dblongitude;
public static ArrayList<Double> latitudearray = new ArrayList<Double>(); Intent intent;
int counter = 0;
@Override
public void onCreate()
{
super.onCreate();
intent = new Intent(BROADCAST_ACTION);
}
public void onStart(Intent intent, int startId)
{
Toast.makeText(getApplicationContext(), "Your location sharing Statted", Toast.LENGTH_SHORT).show();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
listener =new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER , 0, 0, listener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
}
// public int onStartCommand(Intent intent, int flags, int startId)
// {
// return START_STICKY;
// }
//
public IBinder onBind(Intent intent)
{
return null;
}
protected boolean isBetterLocation(Location location, Location currentBestLocation) {
if (currentBestLocation == null) {
// A new location is always better than no location
return true;
}
// Check whether the new location fix is newer or older
long timeDelta = location.getTime() - currentBestLocation.getTime();
boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
boolean isNewer = timeDelta > 0;
// If it's been more than two minutes since the current location, use the new location
// because the user has likely moved
if (isSignificantlyNewer) {
return true;
// If the new location is more than two minutes older, it must be worse
} else if (isSignificantlyOlder)
{
return false;
}
// Check whether the new location fix is more or less accurate
int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
boolean isLessAccurate = accuracyDelta > 0;
boolean isMoreAccurate = accuracyDelta < 0;
boolean isSignificantlyLessAccurate = accuracyDelta > 200;
// Check if the old and new location are from the same provider
boolean isFromSameProvider = isSameProvider(location.getProvider(),currentBestLocation.getProvider());
// Determine location quality using a combination of timeliness and accuracy
if (isMoreAccurate) {
return true;
} else if (isNewer && !isLessAccurate) {
return true;
} else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
return true;
}
return false;
}
private boolean isSameProvider(String provider1, String provider2) {
if (provider1 == null) {
return provider2 == null;
}
return provider1.equals(provider2);
}
public void onDestroy()
{
super.onDestroy();
Toast.makeText(getApplicationContext(), "Your location sharing stoped", Toast.LENGTH_SHORT).show();
locationManager.removeUpdates(listener);
}
public static Thread performOnBackgroundThread(final Runnable runnable) {
final Thread t = new Thread( ) {
@Override
public void run() {
try
{
runnable.run();
} finally
{
}
}
};
t.start();
return t;
}
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(final Location loc) {
// Log.i("**************************************", "Location changed");
if (isBetterLocation(loc, previousBestLocation))
{
double lo = loc.getLatitude();
double log = loc.getLongitude();
double latitude = loc.getLatitude();
double longitude = loc.getLongitude();
// double LatLng=(latitude,longitude);
intent.putExtra("Latitude", loc.getLatitude());
intent.putExtra("Longitude", loc.getLongitude());
intent.putExtra("Provider", loc.getProvider());
sendBroadcast(intent);
Float Speed = ((loc.getSpeed() * 3600) / 1000);
Geocoder geoCoder = new Geocoder(GPSSERVICE.this, Locale.getDefault());
StringBuilder builder = new StringBuilder();
mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(latitude,longitude), 13));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(latitude, longitude)) // Sets the center of the map to location user
.zoom(17) // Sets the zoom
.bearing(180) // Sets the orientation of the camera to east
.tilt(45) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
try {
List<Address> address = geoCoder.getFromLocation(latitude,longitude, 1);
int maxLines = address.get(0).getMaxAddressLineIndex();
for (int i = 0; i < maxLines; i++)
{
local = address.get(0).getSubLocality();
String addressStr = address.get(0).getAddressLine(i);
builder.append(addressStr);
builder.append(" ");
}
String fnialAddress = builder.toString();
SimpleDateFormat sdf = new SimpleDateFormat("hh.mm");
String Time = sdf.format(new Date());
Calendar now = Calendar.getInstance();
now.add(Calendar.MINUTE, -10);
SimpleDateFormat sdff = new SimpleDateFormat("hh:mm:ss aa dd/MM/yyyy");
String currentDateandTime = sdff.format(new Date());
if(mark!=null || myCircle!=null)
{
mark.remove();
myCircle.remove();
}
mark = mGoogleMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title(local + currentDateandTime).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
CircleOptions circleOptions = new CircleOptions()
.center(new LatLng(latitude,longitude)) //set center
.radius(50) //set radius in meters
.fillColor(0x40ff0000) //semi-transparent
.strokeColor(Color.BLUE)
.strokeWidth(0);
myCircle = mGoogleMap.addCircle(circleOptions);
}
catch (IOException e)
{
} catch (NullPointerException e) {
}
}
}
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT).show();
}
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bluebg"
tools:context=".MainActivity" >
<fragment
android:id="@+id/map"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_below="@+id/spr_place_type"
class="com.google.android.gms.maps.SupportMapFragment" />
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.exmaps"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="15"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<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" />
<permission
android:name="com.exmaps.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="com.exmaps.permission.MAPS_RECEIVE" />
<application
android:allowBackup="true"
android:icon="@drawable/eclipsemapicon"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".GPSSERVICE"
android:enabled="true"
android:exported="true" >
</service>
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyB2blzNdI-nRXa7hzgLq5dkEQb4eOUqw2U" />
</application>
</manifest>
screen shots
No comments:
Post a Comment