0

This is my Map Activity class and i have to extract the current location lat n long points and have to show them on map.And i also have incorporated a search box which will display the location of an address on map. Its showing the location but at difference of 200 meter. And when i reopen it, it always show the previous traced location or searched location. I want to show the extracted lat n long points on map.Please Help me out. Thanks in advance..

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

  import android.app.AlertDialog;
  import android.graphics.drawable.Drawable;
 import android.location.Address;
 import android.location.Criteria;
import android.widget.Button;
 import android.widget.EditText;

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.Overlay;
import com.google.android.maps.OverlayItem;

public class MapViewActivity extends MapActivity implements LocationListener {

private MapView mapView;
Button search;
EditText address;
 private LocationManager locationManager;
 @Override
 public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

search=(Button)findViewById(R.id.find_loc);
address=(EditText)findViewById(R.id.enter_address);
search.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        address=(EditText)findViewById(R.id.enter_address);
        if (address.getText().toString().trim().length() == 0) {
            showMessage("Error", "Please enter address!");
            return;
        }
        Geocoder geoCoder = new Geocoder(MapViewActivity.this, 
    Locale.getDefault()); 
        try {
            List<Address> addresses = geoCoder.getFromLocationName(
                    address.getText().toString(), 1);
         // Getting latitude
            double latitude = addresses.get(0).getLatitude();

            // Getting longitude
            double longitude = addresses.get(0).getLongitude();

            if (addresses.size() > 0) {
              GeoPoint p = new GeoPoint(
                        (int) ( latitude * 1E6), 
                        (int) (longitude * 1E6));
           // Getting MapController
            MapController mapController = 
 mapView.getController();

            // Locating the Geographical point in the Map
            mapController.animateTo(p);

            //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 = 
  MapViewActivity.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(p, 
 "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);    
            }    
        } catch (IOException e) {
            e.printStackTrace();                    
        }
        catch(Exception e)
        {
            showMessage("Error", "Address not found!");
            e.printStackTrace();
        }
    }
});
// 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) getSystemService(LOCATION_SERVICE);

// Creating a criteria object to retrieve provider
//Criteria criteria = new Criteria();
final Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);

// 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 onBackPressed() {
    finish();
 }
@Override
public void onDestroy() {
 if (locationManager != null) {
 locationManager.removeUpdates(this);
 }
 super.onDestroy();
  }

 @Override
  public void onLocationChanged(Location 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);        

}

  private void showMessage(final String title, final String message) {
runOnUiThread(new Runnable() {

    public void run() {
        AlertDialog.Builder alert = new AlertDialog.Builder(MapViewActivity.this);
        alert.setTitle(title);
        alert.setPositiveButton("OK", null);
        alert.setMessage(message);
        alert.show();
    }
});
}
    @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      
}

 }

   and this is my CurrentLocationOverlay class


package com.ceolution.bhinstitute.crm;

 import java.util.ArrayList;

import android.graphics.drawable.Drawable;
import android.util.Log;

 import com.google.android.maps.ItemizedOverlay;
 import com.google.android.maps.OverlayItem;

 public class CurrentLocationOverlay extends ItemizedOverlay<OverlayItem> {

private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();

public CurrentLocationOverlay(Drawable defaultMarker) {
    super(boundCenterBottom(defaultMarker));        
}

// Executed, when populate() method is called
@Override
protected OverlayItem createItem(int arg0) {
    return mOverlays.get(arg0);     
}

@Override
public int size() {     
    return mOverlays.size();
}

public void addOverlay(OverlayItem overlay){
    mOverlays.add(overlay);
    populate(); // Calls the method createItem()
}

@Override
protected boolean onTap(int arg0) {
    Log.d("Tapped", mOverlays.get(arg0).getSnippet());
    return true;
}
 }
saba
  • 1
  • 6
  • You get the last location, because you're using `Location location = locationManager.getLastKnownLocation(provider);` and I didn't see anywhere that you use `GPS_PROVIDER` or `NETWORK_PROCIDER`. – g00dy Jul 31 '13 at 06:55
  • So wat shud i use instead? please do tell me as i m new to android. – saba Jul 31 '13 at 07:05
  • @user2523258 please tell me is it return the same location every time which is 200mether away? – Sandeep Jul 31 '13 at 07:09
  • @user2523258 - check this out - http://stackoverflow.com/questions/1513485/how-do-i-get-the-current-gps-location-programmatically-in-android it has everything you need. Also, you can check the tutorial here -> http://webdesignergeeks.com/mobile/android/geting-current-location-in-android-application-using-gps/ . – g00dy Jul 31 '13 at 07:22
  • @DeepSan:- first time it shows 200 m difference and den it is showing the previous traced location. I want to extract the lat n long of a location and want to show that on a map. everytym a user chnage its location it shud be shown on map.. thanks in advance – saba Jul 31 '13 at 07:34
  • @g00dy: i want to show this current location in map. everytime.m a user changes its location that should be shown on map. please help me out.. thanks – saba Jul 31 '13 at 07:36
  • If you implement properly the code from the tutorials (this includes the method `onLocationChanged`), this should update the location realtime. – g00dy Jul 31 '13 at 07:41
  • @saba the code that you have posted is the complete code? – Sandeep Jul 31 '13 at 08:50
  • @DeepSan yes its complete. both the classes i.e Map activity and locationoverlay. – saba Jul 31 '13 at 09:19
  • ok let me check wait for some time.. – Sandeep Jul 31 '13 at 09:20

1 Answers1

0
    // Getting LocationManager object from System Service LOCATION_SERVICE
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);



    // getting GPS status
    isGPSEnabled = locationManager
            .isProviderEnabled(LocationManager.GPS_PROVIDER);

    String provider;
    if(!isGPSEnabled)
    {
        provider = LocationManager.NETWORK_PROVIDER;
    }
    else
        provider=LocationManager.GPS_PROVIDER;


    locationManager.requestLocationUpdates(provider, 20000, 0, this);

use above code after

// Setting Zoom Controls on MapView
        mapView.setBuiltInZoomControls(true);

hope this will help and also you can give alert to user to enable gps.

Sandeep
  • 2,573
  • 3
  • 21
  • 28
  • i have tried this code but its till showing 200 m distance difference. can u please give me your email id so dat i can send you the code. please do tell me – saba Jul 31 '13 at 12:11
  • I have send you a mail at your given id. please check and give me solution. Thanks in advance – saba Jul 31 '13 at 18:57