Implement google map like Uber - java

I am completely new to android.I am trying to implement a draggable google map like uber app.I have found out a code from somewhere,But when I try running few issues were coming like
Error:(24, 37) error: cannot find symbol class GooglePlayServicesClient
Error:(26, 39) error: cannot find symbol class LocationClient
In my dependencies I have added
compile 'com.google.android.gms:play-services:8.4.0'
Following is the code I have used.
package com.rakyow.taxifinder.taxifinder;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.app.Dialog;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnCameraChangeListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends Activity implements
ConnectionCallbacks, OnConnectionFailedListener {
// A request to connect to Location Services
private LocationRequest mLocationRequest;
GoogleMap mGoogleMap;
public static String ShopLat;
public static String ShopPlaceId;
public static String ShopLong;
// Stores the current instantiation of the location client in this object
private GoogleApiClient mLocationClient;
boolean mUpdatesRequested = false;
private TextView markerText;
private LatLng center;
private LinearLayout markerLayout;
private Geocoder geocoder;
private List<Address> addresses;
private TextView Address;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homepage);
markerText = (TextView) findViewById(R.id.locationMarkertext);
Address = (TextView) findViewById(R.id.adressText);
markerLayout = (LinearLayout) findViewById(R.id.locationMarker);
// Getting Google Play availability status
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
// Create a new global location parameters object
mLocationRequest = LocationRequest.create();
/*
* Set the update interval
*/
mLocationRequest.setInterval(GData.UPDATE_INTERVAL_IN_MILLISECONDS);
// Use high accuracy
mLocationRequest
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the interval ceiling to one minute
mLocationRequest
.setFastestInterval(GData.FAST_INTERVAL_CEILING_IN_MILLISECONDS);
// Note that location updates are off until the user turns them on
mUpdatesRequested = false;
/*
* Create a new location client, using the enclosing class to handle
* callbacks.
*/
mLocationClient = new GoogleApiClient(this, this, this);
mLocationClient.connect();
}
}
private void stupMap() {
try {
LatLng latLong;
// TODO Auto-generated method stub
mGoogleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// Enabling MyLocation in Google Map
mGoogleMap.setMyLocationEnabled(true);
if (mLocationClient.getLastLocation() != null) {
latLong = new LatLng(mLocationClient.getLastLocation()
.getLatitude(), mLocationClient.getLastLocation()
.getLongitude());
ShopLat = mLocationClient.getLastLocation().getLatitude() + "";
ShopLong = mLocationClient.getLastLocation().getLongitude()
+ "";
} else {
latLong = new LatLng(12.9667, 77.5667);
}
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLong).zoom(19f).tilt(70).build();
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
// Clears all the existing markers
mGoogleMap.clear();
mGoogleMap.setOnCameraChangeListener(new OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition arg0) {
// TODO Auto-generated method stub
center = mGoogleMap.getCameraPosition().target;
markerText.setText(" Set your Location ");
mGoogleMap.clear();
markerLayout.setVisibility(View.VISIBLE);
try {
new GetLocationAsync(center.latitude, center.longitude)
.execute();
} catch (Exception e) {
}
}
});
markerLayout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
LatLng latLng1 = new LatLng(center.latitude,
center.longitude);
Marker m = mGoogleMap.addMarker(new MarkerOptions()
.position(latLng1)
.title(" Set your Location ")
.snippet("")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.add_marker)));
m.setDraggable(true);
markerLayout.setVisibility(View.GONE);
} catch (Exception e) {
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
stupMap();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
private class GetLocationAsync extends AsyncTask<String, Void, String> {
// boolean duplicateResponse;
double x, y;
StringBuilder str;
public GetLocationAsync(double latitude, double longitude) {
// TODO Auto-generated constructor stub
x = latitude;
y = longitude;
}
#Override
protected void onPreExecute() {
Address.setText(" Getting location ");
}
#Override
protected String doInBackground(String... params) {
try {
geocoder = new Geocoder(MainActivity.this, Locale.ENGLISH);
addresses = geocoder.getFromLocation(x, y, 1);
str = new StringBuilder();
if (geocoder.isPresent()) {
Address returnAddress = addresses.get(0);
String localityString = returnAddress.getLocality();
String city = returnAddress.getCountryName();
String region_code = returnAddress.getCountryCode();
String zipcode = returnAddress.getPostalCode();
str.append(localityString + "");
str.append(city + "" + region_code + "");
str.append(zipcode + "");
} else {
}
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String result) {
try {
Address.setText(addresses.get(0).getAddressLine(0)
+ addresses.get(0).getAddressLine(1) + " ");
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
}
My requirement is something similar to this .
Please help me in solving this issue.Any help would be appreciated.
Thanks in advance

I recommend that you use GoogleApiClient because LocationClient is no longer supported in newer versions of play-services they removed it starting Google Play Services 6.5.87 if I am not mistaken. Here is the link for the example implementation. If you really want to use LocationClient, which I do not recommend, you can use an older version of the play-services

cannot find symbol class GooglePlayServicesClient Error:(
GooglePlayServicesClient was removed. The documentation explicitly says that you should be using GoogleApiClient
Note: If you have an existing app that connects to Google Play
services with a subclass of GooglePlayServicesClient, you should
migrate to GoogleApiClient as soon as possible.
here you can find more about it.

Use GoogleApiClient instead of Location Client.
LocationClient is deprecated. The replacement class is the
GoogleApiClient. It has similar functions so its easy to replace.
Source

Related

Calculate Time and distance and draw a path between two draggable markers in Google maps v2

Need your help!!..I am building an android app using Google API V2. I have managed to place two markers on the map and also get there location. What I mainly want to do now is to calculate their distance and time like we do in the Google maps and draw a path between them. How can I achieve that?
a-) Can I do it without using JSON? I just know JAVA not java script so help please.
b-) Who ever answer it, Please if you can, Elaborate the steps taken in the code comments?
Here is my Maps ACtivity
--
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.IntentSender;
import android.graphics.Color;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
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.BitmapDescriptorFactory;
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 com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class MapsActivity extends FragmentActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,LocationListener,GoogleMap.OnMarkerClickListener, GoogleMap.OnInfoWindowClickListener, GoogleMap.OnMapLongClickListener, GoogleMap.OnMarkerDragListener {
private GoogleApiClient mGoogleApiClient;
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
public static final String TAG = MapsActivity.class.getSimpleName();
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private LocationRequest mLocationRequest;
private LocationRequest LocationDrop;
// TextView currentloc;
String filterAddress = "";
String DropoffAdress = "";
String DraggedDroppOff= "";
String dragendaddress = "";
// TextView dropOffaddress;
double currentLatitude;
double currentLongitude;
double draglat;
double draglng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
// tvLocInfo = (TextView) findViewById(R.id.locinfo);
mMap.setOnMapLongClickListener(this);
mMap.setOnMarkerDragListener(this);
mMap.setOnMarkerClickListener(this);
// LocationDrop = LocationRequest.create().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY).setInterval(10 * 1000).setFastestInterval(1 * 1000);
mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
mGoogleApiClient.connect();
}
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* call {#link #setUpMap()} once when {#link #mMap} is not null.
* <p>
* If it isn't installed {#link SupportMapFragment} (and
* {#link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
* install/update the Google Play services APK on their device.
* <p>
* A user can return to this FragmentActivity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the FragmentActivity may not
* have been completely destroyed during this process (it is likely that it would only be
* stopped or paused), {#link #onCreate(Bundle)} may not be called again so we should call this
* method in {#link #onResume()} to guarantee that it will be called.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* <p>
* This should only be called once and when we are sure that {#link #mMap} is not null.
*/
private void setUpMap() {
// mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Pick Me").snippet(filterAddress));
}
#Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "Location services connected.");
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location != null) {
// LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
handleNewLocation(location);
}
else {
handleNewLocation(location);
}
}
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
MarkerOptions optionsA = new MarkerOptions().position(latLng).title("Pick Me").snippet(filterAddress).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
mMap.addMarker(optionsA).setDraggable(false);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(15);
// mMap.moveCamera(center);
mMap.animateCamera(zoom);
// mMap.setOnMarkerDragListener();
Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(currentLatitude,currentLongitude,1);
// List<Address> dropaddress = geoCoder.getFromLocation(laterLongitut,laterlatitude,1);
if (addresses.size() > 0) {
for (int i = 0; i < addresses.get(0).getMaxAddressLineIndex(); i++)
filterAddress += addresses.get(0).getAddressLine(i) + " ";
Log.e("My current address is 2", filterAddress );
}
}catch (IOException ex){
ex.printStackTrace();
}catch (Exception e2){
e2.printStackTrace();
}
// currentloc = (TextView) findViewById(R.id.txmarker);
// currentloc.setText("Address" + filterAddress);
Log.e("My current address is 1", filterAddress);
// Log.e("My later address is 2", DropoffAdress );
Toast.makeText(getBaseContext(),filterAddress,Toast.LENGTH_LONG).show();
}
#Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Location services suspended. Please reconnect.");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
#Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
public void onBackPressed(){
Intent intent = new Intent(this,TurnOnGps.class);
startActivity(intent);
setContentView(R.layout.activity_turn_on_gps);
}
#Override
public void onInfoWindowClick(Marker marker) {
marker.setTitle(filterAddress);
}
#Override
public void onMapLongClick(LatLng latLng) {
MarkerOptions options2 = new MarkerOptions();
options2.position(latLng);
options2.title("Drop ME").snippet("Dragg Me ");
options2.draggable(true);
mMap.addMarker(options2);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(15);
Toast.makeText(getBaseContext(),"Please Drag Marker to set your Drop OFF",Toast.LENGTH_LONG).show();
// mMap.moveCamera(center);
mMap.animateCamera(zoom);
/* double updateddroplat = latLng.latitude;
double updateddroplng = latLng.longitude;
//Converting the latlngs to a string through geoencoder
LatLng latLng1 = new LatLng(updateddroplat,updateddroplng);
Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(updateddroplat,updateddroplng,1);
if(addresses.size() > 0){
for (int i=0; i < addresses.get(0).getMaxAddressLineIndex(); i++)
DropoffAdress += addresses.get(0).getAddressLine(i) + "";
Log.e("My DroppOff Location is" , DropoffAdress);
}
}catch (IOException ex){
ex.printStackTrace();
}catch (Exception e2){
e2.printStackTrace();
}
Log.e("My DropOff Location is" , DropoffAdress);
Toast.makeText(getBaseContext(),DropoffAdress,Toast.LENGTH_LONG).show();
*/
}
#Override
public void onMarkerDragStart(Marker marker) {
marker.setSnippet("Please Drag me to set your Drop OFF");
}
#Override
public void onMarkerDrag(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
DropoffAdress = dragendaddress;
Log.e("My DroppOff Location is" , DraggedDroppOff);
LatLng dragposition = marker.getPosition();
draglat = dragposition.latitude;
draglng = dragposition.longitude;
LatLng latLng1 = new LatLng(draglat, draglng);
marker.getId();
// marker.getSnippet();
marker.setSnippet(dragendaddress);
marker.setTitle("Drop ME");
Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(draglat,draglng,1);
if(addresses.size() > 0){
for (int i=0; i < addresses.get(0).getMaxAddressLineIndex(); i++){
dragendaddress += addresses.get(0).getAddressLine(i) + "";
Log.e("My DroppOff Location is", dragendaddress);
}
Toast.makeText(getBaseContext(),dragendaddress,Toast.LENGTH_LONG).show();
}
}catch (IOException ex){
ex.printStackTrace();
}catch (Exception e2){
e2.printStackTrace();
}
}
#Override
public boolean onMarkerClick(Marker marker ) {
Log.e("am in markerclick event","");
String Title = marker.getTitle();
String Snippet = marker.getSnippet();
Log.e("I am in onMarkerClick", Title);
if(Title.equals("Pick Me")){
marker.setSnippet(filterAddress);
Toast.makeText(getBaseContext(),filterAddress,Toast.LENGTH_LONG).show();
Log.e("I am in onMarkerClick", Title);
}else if(Title.equals("Drop ME")){
marker.setSnippet(dragendaddress);
Toast.makeText(getBaseContext(),dragendaddress,Toast.LENGTH_LONG).show();
}
try {
Polyline polyline = mMap.addPolyline(new PolylineOptions().add(new LatLng(currentLatitude, currentLongitude), new LatLng(draglat, draglng)).width(10).color(Color.RED));
}catch (Exception e){
e.printStackTrace();
}
return false;
}
calculating the distance ::
public float distance (LatLng point1, LatLng point2 )
{
double earthRadius = 3958.75;
double latDiff = Math.toRadians(point2.latitude - point1.latitude);
double lngDiff = Math.toRadians(point2.longitude - point2.longitude);
double a = Math.sin(latDiff /2) * Math.sin(latDiff /2) +
Math.cos(Math.toRadians(point1.latitude)) * Math.cos(Math.toRadians(point2.latitude)) *
Math.sin(lngDiff /2) * Math.sin(lngDiff /2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double distance = earthRadius * c;
int meterConversion = 1609;
return new Float(distance).floatValue();
}
and to draw a line add the points to a list then use the polyline function .
Ok Firstly thanks all you guys for being a support. I finally got the solution to my problem with blessings and a bit of my own RND..
http://wptrafficanalyzer.in/blog/route-between-two-locations-with-waypoints-in-google-map-android-api-v2/
This greatly solved the Direction Parsing issue.
And i molded my code and added the methods from the Maps activity and JSON class.
Which solved the problem.
Happy :)
Thanks for taking the time..
+Any one having the same issue can post there problem in the comments i would try to answer it. Through what ever small i have learnt from solving this problem..
You can use code here. In this code distanceText gives distance between two points and timeText gives travelling time.

How to track the distance when user running/ walking

Im currently doing an apps that can track running distance.
My idea is when i click start, i will record the position that i start running, then when i click stop, it will record the position that i end my running. Then calculate the distance between this 2 point.
I don't know why my distance result keep showing me 0km no matter how i run. Please help me see if gt any problems~
package com.example.ifitness;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.SupportMapFragment;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class calorieburn extends ActionBarActivity implements LocationListener{
private GoogleMap map;
private Location startLocation;
private Location endLocation;
private double latA;
private double longA;
private double latB;
private double longB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calorieburn);
SetupMap();
Button start = (Button) findViewById(R.id.start);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
latA = startLocation.getLatitude();
longA = startLocation.getLongitude();
TextView distance = (TextView) findViewById(R.id.distance);
distance.setText("0 km");
TextView calorie = (TextView) findViewById(R.id.calorie);
calorie.setText("0 cal");
}
});
Button stop = (Button) findViewById(R.id.stop);
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
latB = endLocation.getLatitude();
longB = endLocation.getLongitude();
TextView distance = (TextView) findViewById(R.id.distance);
distance.setText(String.valueOf(distance(latA,longA,latB,longB)+ "km"));
TextView calorie = (TextView) findViewById(R.id.calorie);
calorie.setText(String.valueOf(distance(latA,longA,latB,longB)+ "cal"));
}
});
}
public double calories(double distance){
double calories = 0;
calories = distance * 100;
return calories;
}
public static void distanceBetween(){
}
public double distance(double lat,double lng,double latitude,double longtitude){
Location locA = new Location("locA");
locA.setLatitude(lat);
locA.setLongitude(lng);
Location locB = new Location("locB");
locB.setLatitude(latitude);
locB.setLongitude(longtitude);
double distance = locA.distanceTo(locB);
return distance;
}
private void SetupMap() {
if (map == null){
// Getting reference to the SupportMapFragment of activity_main.xml
SupportMapFragment mf = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// get google map from the fragment
map = mf.getMap();
}
if (map !=null ){
// Enabling MyLocation Layer of Google Map
map.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String bestprovider = lm.getBestProvider(criteria,false);
String provider = LocationManager.NETWORK_PROVIDER;
if (provider == null){
onProviderDisabled(provider);
}
// Getting Current Location
Location loc = lm.getLastKnownLocation(bestprovider);
if (loc != null){
onLocationChanged(loc);
}
map.setOnMapLongClickListener(onLongClickMapSettings());
}
}
private OnMapLongClickListener onLongClickMapSettings() {
// TODO Auto-generated method stub
return new OnMapLongClickListener(){
#Override
public void onMapLongClick(LatLng arg0) {
// TODO Auto-generated method stub
Log.i(arg0.toString(), "User Long CLicked");
}
};
}
#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
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
map.animateCamera(CameraUpdateFactory.zoomTo(17));
}
private void makeUseOfNewLocation(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
}

Unable to send GPS coordinates to server

I am trying to send GPS coordinates to server got by my app,it is showing GPS coordinates correctly, but unable to send it to server, the problem is in my MainActivity.java
Here is my code
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.NameValuePair;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
int lat,lng;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_location);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
lat = (int) (location.getLatitude());
lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
private class LoadServerASYNC extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return null;
}
void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://182.18.144.140:80"); //your php file path
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("lat", "1.0256"));
nameValuePairs.add(new BasicNameValuePair("lng", "1.0256"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
}
I am not getting what is the problem
You are not initializing and executing the LoadServerAsync anywhere.
If you want to send coordinates every time you update the text views, you should do this:
#Override
public void onLocationChanged(Location location) {
lat = (int) (location.getLatitude());
lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
LoadServerASYNC task = new LoadServerASYNC();
task.execute();
}
And you should call postData method inside doInBackground();

Data not changed while inserting data from android to mysql database

I have a problem in inserting data (latitude and longitude) to mysql. when I first run the app, the lat and long are inserted but when I updated the location (lat and long) and insert the data again, only the longitude changes, and the latitude stays the same value as the previous data inserted. I'm totally confused why it doesnt work. I'd be very glad if anyone could help me with this.
This is my code
package com.android.tyegah;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class TyegahActivity extends Activity {
private LocationManager locationManager;
private Location latestLocation;
private double lat;
private double longi;
private Button updateButton;
private TextView locUpdate;
public String url = "http://servername/file.php";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
locationManager =(LocationManager)getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,onLocationChange);
locUpdate = (TextView)findViewById(R.id.locUpdate);
updateButton = (Button)findViewById(R.id.updateButton);
updateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,onLocationChange);
if (latestLocation.getLatitude() != lat && latestLocation.getLongitude() != longi ) {
lat = latestLocation.getLatitude();
longi = latestLocation.getLongitude();
}
String latitude = Double.toString(lat);
String longitude = Double.toString(longi);
url += "?latitude=" + latitude + "&longitude=" + longitude;
locUpdate.setText(latitude + "," + longitude);
getRequest(url);
Toast.makeText(getBaseContext(),
"Location updated : Lat: " + latestLocation.getLatitude() +
" Lng: " + latestLocation.getLongitude(),
Toast.LENGTH_LONG).show();
}
});
}
public void getRequest(String Url) {
// TODO Auto-generated method stub
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
try {
HttpResponse response = client.execute(request);
} catch (Exception ex) {
locUpdate.setText(ex.toString());
}
}
LocationListener onLocationChange = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
latestLocation = location;
if (latestLocation.getLatitude() != lat && latestLocation.getLongitude() != longi ) {
Toast.makeText(getBaseContext(),
"Location updated : Lat: " + latestLocation.getLatitude() +
" Lng: " + latestLocation.getLongitude(),
Toast.LENGTH_LONG).show();
}
}
};
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, onLocationChange);
}
}
This is the php file :
<?php
mysql_connect("localhost","root","");
mysql_select_db("php");
$longitude = $_GET['longitude'];
$latitude = $_GET['latitude'];
if($latitude && $longitude){
$string= "insert into table (latitude, longitude)values('".$latitude."','".$longitude."')";
mysql_query($string);
}
mysql_close();
?>
just change two lines and try it
in android
u have written
if (latestLocation.getLatitude() != lat && latestLocation.getLongitude() != longi )
instead that write
if (latestLocation.getLatitude() != lat || latestLocation.getLongitude() != longi )
AND in php
u have putten
$string= "insert into table (latitude, longitude)values('".$latitude."','".$longitude."')";
instead put
$string= "insert into table (latitude, longitude) values('".$latitude."','".$longitude."')";
try it, i think it'll work
You are updating url on onCreate() method and please check Activity life cycle onCreate() method will call first time when activity is created or activity is re created.
I will suggest you to make a call back mechanism to fetch location data whenever you are creating url for server request.

How to Disable Android LocationListener when application is closed

I have a class which handle a location service called MyLocationManager.java
this is the code :
package com.syariati.childzone;
import java.util.List;
import java.util.Locale;
import android.content.Context;
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;
public class MyLocationManager {
private Context context;
private double myLat = 0.0;
private double myLon = 0.0;
private LocationManager locationManager = null;
private Location location = null;
private Criteria criteria;
private String locationName = null;
public MyLocationManager(Context ctx) {
this.context = ctx;
}
private String setCriteria() {
this.criteria = new Criteria();
this.criteria.setAccuracy(Criteria.ACCURACY_FINE);
this.criteria.setAltitudeRequired(false);
this.criteria.setBearingRequired(false);
this.criteria.setCostAllowed(true);
this.criteria.setPowerRequirement(Criteria.POWER_LOW);
return locationManager.getBestProvider(criteria, true);
}
public double getMyLatitude() {
return this.myLat;
}
public double getMyLongitude() {
return this.myLon;
}
public String getLocation() {
return this.locationName;
}
public void onLocationUpdate() {
locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
String provider = setCriteria();
location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider, 1000, 0,
new MyLocationListener());
}
private void updateWithNewLocation(Location location) {
if (location != null) {
this.myLat = location.getLatitude();
this.myLon = location.getLongitude();
// Toast.makeText(this.context,
// "Lokasi Anda:\n" + this.myLat + "\n" + this.myLon,
// Toast.LENGTH_LONG).show();
getLocationName(this.myLat, this.myLon);
} else {
Toast.makeText(this.context, "Lokasi Anda Tidak Diketahui",
Toast.LENGTH_SHORT).show();
}
}
private void getLocationName(double lat, double lon) {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
try {
List<Address> adresses = geocoder.getFromLocation(lat, lon, 1);
StringBuilder sb = new StringBuilder();
if (adresses.size() > 0) {
Address address = adresses.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
sb.append(address.getAddressLine(i)).append("\n");
sb.append(address.getCountryName()).append("\n");
}
this.locationName = sb.toString();
// Toast.makeText(context, sb.toString(), Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location newLocation) {
// TODO Auto-generated method stub
myLat = newLocation.getLatitude();
myLon = newLocation.getLongitude();
getLocationName(myLat, myLon);
Toast.makeText(context,
"Lokasi terupdate\nLat: " + myLat + "\nLon: " + myLon,
Toast.LENGTH_SHORT).show();
}
#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
}
}
}
which has an Inner class that implements location listener on it. So far, it works. It listen the location with no problem. However, when I exit my apps, it doesn't completely stop the listen the location. As you see from this code :
#Override
public void onLocationChanged(Location newLocation) {
// TODO Auto-generated method stub
myLat = newLocation.getLatitude();
myLon = newLocation.getLongitude();
getLocationName(myLat, myLon);
Toast.makeText(context,
"Lokasi terupdate\nLat: " + myLat + "\nLon: " + myLon,
Toast.LENGTH_SHORT).show();
}
while the location is updated, the toast will be shown, and it still appear when the location is updated. Even when I've closed the application.
How to stop the location listener completely in my case.
This one helped me to stop the updat :
android how to stop gps
You may call removeUpdates on your LocationManager.
public void removeUpdates (PendingIntent intent)
Removes any current registration for location updates of the current
activity with the given PendingIntent. Following this call, updates
will no longer occur for this intent.
Parameters:
intent {#link PendingIntent} object that no longer needs location
updates
Throws:
IllegalArgumentException if intent is null
See here: http://developer.android.com/reference/android/location/LocationManager.html#removeUpdates(android.app.PendingIntent)
Updated:
In this case, you may change this line:
locationManager.requestLocationUpdates(provider, 1000, 0,
new MyLocationListener());
to:
MyLocationListener myLL = new MyLocationListener();
locationManager.requestLocationUpdates(provider, 1000, 0,
myLL);
When you want to remove your listener call as below:
locationManager.removeUpdates(myLL);

Categories

Resources