Android map with different location with different marker image - android

I'm doing map application in android.For that,i need to show current location with one marker image.And when i type any address on top editText box,i need to show tht location with different marker image + i can change that second marker into tapped locations.For me,initially it shows current location with one marker well.But when i type.,while second marker has come.,that first marker(current location) will disapper.I want to have both two markers on view.How could i do that?
My code:
Handler h = new Handler() {
// Invoked by the method onTap()
// in the class CurrentLocationOverlay
#Override
public void handleMessage(Message msg) {
Bundle data = msg.getData();
// Getting the Latitude of the location
int latitude = data.getInt("latitude");
// Getting the Longitude of the location
int longitude = data.getInt("longitude");
// Show the location in the Google Map
showLocation(latitude, longitude);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Getting reference to map_view available in activity_main.xml
mapView = (MapView) findViewById(R.id.map_view);
// Getting reference to tv_location available in activity_main.xml
tvLocation = (TextView) findViewById(R.id.tv_location);
initLocationManager();
// Default Latitude
int latitude = 28426365;
// Default Longitude
int longitude = 77320393;
// Show the location in the Google Map
showLocation(latitude, longitude);
}
private void initLocationManager() {
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 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.ic_launcher);
// 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
}
private void showLocation(int latitude, int longitude) {
// Setting Latitude and Longitude in TextView
tvLocation.setText("Latitude:" + latitude / 1e6 + "," + "Longitude:"
+ longitude / 1e6);
// Setting Zoom Controls
mapView.setBuiltInZoomControls(true);
// Getting the MapController
MapController mapController = mapView.getController();
// Getting Overlays of the map
List<Overlay> overlays = mapView.getOverlays();
// Getting Drawable object corresponding to a resource image
Drawable drawable = getResources().getDrawable(R.drawable.marker);
// Creating an ItemizedOverlay
TouchedLocationOverlay locationOverlay = new TouchedLocationOverlay(
drawable, h);
// Getting the MapController
MapController mc = mapView.getController();
// Creating an instance of GeoPoint, to display in Google Map
GeoPoint p = new GeoPoint(latitude, longitude);
// Locating the point in the Google Map
mc.animateTo(p);
// Creating an OverlayItem to mark the point
OverlayItem overlayItem = new OverlayItem(p, "Item", "Item");
// Adding the OverlayItem in the LocationOverlay
locationOverlay.addOverlay(overlayItem);
// Clearing the overlays
overlays.clear();
// Adding locationOverlay to the overlay
overlays.add(locationOverlay);
// Redraws the map
mapView.invalidate();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
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, double lat, double lang) {
super(marker);
boundCenterBottom(marker);
items.add(new OverlayItem(getPoint(lat, lang), "", ""));
populate();
}
public SitesOverlay(Drawable marker, double[] latitude,
double[] longitude) {
super(marker);
// boundCenterBottom(marker);
for (int i = 0; i < latitude.length; i++) {
items.add(new OverlayItem(getPoint(latitude[i], longitude[i]),
"", ""));
}
populate();
}
#Override
protected OverlayItem createItem(int i) {
return (items.get(i));
}
#Override
protected boolean onTap(int i) {
/*
* Toast.makeText(LocationBasedServicesV2.this,
* items.get(i).getSnippet(), Toast.LENGTH_SHORT).show();
*/
return (true);
}
#Override
public int size() {
return (items.size());
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
TochedLocation:
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
private Handler handler;
public TouchedLocationOverlay(Drawable defaultMarker,Handler h) {
super(boundCenterBottom(defaultMarker));
// Handler object instantiated in the class MainActivity
this.handler = h;
}
// 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(); // Invokes the method createItem()
}
// This method is invoked, when user tap on the map
#Override
public boolean onTap(GeoPoint p, MapView map) {
List<Overlay> overlays = map.getOverlays();
// Creating a Message object to send to Handler
Message message = new Message();
// Creating a Bundle object ot set in Message object
Bundle data = new Bundle();
// Setting latitude in Bundle object
data.putInt("latitude", p.getLatitudeE6());
// Setting longitude in the Bundle object
data.putInt("longitude", p.getLongitudeE6());
// Setting the Bundle object in the Message object
message.setData(data);
// Sending Message object to handler
handler.sendMessage(message);
return super.onTap(p, map);
}
Thanks.

If you want the first overlay to be fixed which is your current location overlay, try with the below code and let me know.
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.remove(1); // Here instead of clearing all overlays, just clear the last added overlay.
listOfOverlays.add(mapOverlay); // Then you can add a new overlay.
mapView.invalidate();
or
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listOfOverlays = mapView.getOverlays();
if(listOfOverlays.size() > 1)
listOfOverlays.remove(listOfOverlays.size()-1); // Here instead of clearing all overlays, just clear the last added overlay.
listOfOverlays.add(mapOverlay); // Then you can add a new overlay.
mapView.invalidate();

Related

Getting 200 meter distance difference from the current location in GPS with map

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;
}
}
// 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.

get the latitude and longitude of a clicked location on the map in osmdroid

I've managed to write an android app using it to trace user location and show it on the map using a marker. Here is the relevant code:
public class MainActivity extends Activity implements LocationListener {
public MapView mapView;
private LocationManager locationManager;
MyItemizedOverlay myItemizedOverlay = null;
Drawable marker;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapView = (MapView) this.findViewById(R.id.mapview);
mapView.setUseDataConnection(false);
mapView.setClickable(true);
mapView.setBuiltInZoomControls(true);
mapView.setMultiTouchControls(true);
mapView.setUseDataConnection(false);
mapView.setFocusable(true);
mapView.setFocusableInTouchMode(true);
mapView.getController().setZoom(16); // set initial zoom-level, depends
// on your need
marker = getResources().getDrawable(android.R.drawable.star_on);
int markerWidth = 1;
int markerHeight = 1;
marker.setBounds(0, markerHeight, markerWidth, 0);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, this); // You can also use LocationManager.GPS_PROVIDER and
// LocationManager.PASSIVE_PROVIDER
}
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude() * 1E6);
int lng = (int) (location.getLongitude() * 1E6);
GeoPoint point = new GeoPoint(lat, lng);
mapView.getController().setCenter(point);
mapView.getController().animateTo(point);
mapView.invalidate();
ResourceProxy resourceProxy = new DefaultResourceProxyImpl(
getApplicationContext());
myItemizedOverlay = new MyItemizedOverlay(marker, resourceProxy);
mapView.getOverlays().clear();
mapView.getOverlays().add(myItemizedOverlay);
myItemizedOverlay.addItem(point, "myPoint1", "myPoint1");
TextView tv1 = (TextView) findViewById(R.id.myLat);
tv1.setText("Lat is " + lat);
TextView tv2 = (TextView) findViewById(R.id.myLong);
tv2.setText("Long is " + lng);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
Now I need a way of getting latitude and longitude properties of a clicked location on the map.
I mean I need something similar to the following code(which exists for google map api) in osmdroid.
google.maps.event.addListener(map, 'click', function(event) {
YourHandler(event.latLng);});
You have to create an Overlay and override the onSingleTapConfirmed.
Try this:
Overlay touchOverlay = new Overlay(this){
ItemizedIconOverlay<OverlayItem> anotherItemizedIconOverlay = null;
#Override
protected void draw(Canvas arg0, MapView arg1, boolean arg2) {
}
#Override
public boolean onSingleTapConfirmed(final MotionEvent e, final MapView mapView) {
final Drawable marker = getApplicationContext().getResources().getDrawable(R.drawable.markericon);
Projection proj = mapView.getProjection();
GeoPoint loc = (GeoPoint) proj.fromPixels((int)e.getX(), (int)e.getY());
String longitude = Double.toString(((double)loc.getLongitudeE6())/1000000);
String latitude = Double.toString(((double)loc.getLatitudeE6())/1000000);
System.out.println("- Latitude = " + latitude + ", Longitude = " + longitude );
ArrayList<OverlayItem> overlayArray = new ArrayList<OverlayItem>();
OverlayItem mapItem = new OverlayItem("", "", new GeoPoint((((double)loc.getLatitudeE6())/1000000), (((double)loc.getLongitudeE6())/1000000)));
mapItem.setMarker(marker);
overlayArray.add(mapItem);
if(anotherItemizedIconOverlay==null){
anotherItemizedIconOverlay = new ItemizedIconOverlay<OverlayItem>(getApplicationContext(), overlayArray,null);
mapView.getOverlays().add(anotherItemizedIconOverlay);
mapView.invalidate();
}else{
mapView.getOverlays().remove(anotherItemizedIconOverlay);
mapView.invalidate();
anotherItemizedIconOverlay = new ItemizedIconOverlay<OverlayItem>(getApplicationContext(), overlayArray,null);
mapView.getOverlays().add(anotherItemizedIconOverlay);
}
// dlgThread();
return true;
}
};
mapView.getOverlays().add(touchOverlay);
If you implement MapEventsReceiver you can use the singleTapConfirmedHelper() function which directly gives you a GeoPoint object of the clicked location. Here is an example:
public class MapActivity extends AppCompatActivity implements MapEventsReceiver {
...
#Override
public boolean singleTapConfirmedHelper(GeoPoint p) {
mapController.animateTo(p);
return true;
}
}

Exceptions when trying to get location

I want to get the current position (longitude and longitude) but I am getting some errors in the code.
1. map_view , activity_maintv_location ,cur_position cannot be resolved or is not a field.
Here is my code:
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
}
}
You seem to have grabbed this code and pasted it in your project's Activity. You seem to have, however, not added the other resources. If this is from a website, post a link to that website in the OP.
For instance, consider the error on map_view as stated in the OP refers to this line of code:
mapView = (MapView) findViewById(R.id.map_view);
And the error for cur_position refers to this line:
Drawable drawable = this.getResources().getDrawable(R.drawable.cur_position);
Verify that a MapView with the id of map_view exists in your layout XML activity_main. As for the Drawable cur_position, ensure that you have image resource (I am assuming) in either of the Drawable folders in your Project.
The other activity_maintv_location doesn't appear in the code posted above, but either of the suggestions above will fix that one too.
try this and your Activity must be implements like this implements LocationListener {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
lat = (double) (location.getLatitude());
lng = (double) (location.getLongitude());
Log.i(TAG, "Lattitude:" + lat);
Log.i(TAG, "Longitude:" + lng);
Toast.makeText( this, "Current location:\nLatitude: " + lat + "\n" + "Longitude: " + lng, Toast.LENGTH_LONG).show();
// create geo point
GeoPoint point = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
MapController controller = mapview.getController();
controller.animateTo(point);
controller.setZoom(13);
mapview.setBuiltInZoomControls(true);
drawable = getResources().getDrawable(R.drawable.marker);
OverlayItem overlayItem = new OverlayItem(point, "", "");
itemizedOverlay = new SimpleItemizedOverlay(drawable, mapview);
itemizedOverlay.addOverlay(overlayItem);
mapOverlays = mapview.getOverlays();
mapview.getOverlays().add(itemizedOverlay);
mapview.invalidate();
} else {
System.out.println("Location not avilable");
}
locationManager.removeUpdates(this);
}

How to get current location on google mapview in android [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
In this my code i did not understand where i did mistake in my code .I did not get current location on map view with pin point image. How to get the Latitude & Latitude and pass in Geo point. then pass the value OverlayItem ..
public class HelloGoogleMaps2 extends MapActivity implements LocationListener{
private LocationManager locationManager;
private String provider;
int lat;
int lng;
MyLocationOverlay myLocOverlay;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
// 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, true);
Location location = locationManager.getLastKnownLocation(provider);
Log.d("provider ","Provider "+provider);
Log.d("provider ","Provider "+provider);
Log.d("provider ","Provider "+provider);
Log.d("location","Location "+location);
Log.d("location","Location "+location);
Log.d("location","Location "+location);
// 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");
}
List<Overlay> mapOverlays = mapView.getOverlays();
myLocOverlay = new MyLocationOverlay(this, mapView);
mapOverlays.add(myLocOverlay);
myLocOverlay.enableMyLocation();
GeoPoint point = new GeoPoint(lat, lng);
// mc.setCenter(point);
// mapView.invalidate();
Drawable drawable = this.getResources().getDrawable(R.drawable.ic_launcher);
HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable);
GeoPoint point = new GeoPoint(lat,lng);
OverlayItem overlayitem = new OverlayItem(point, "Hola, Mundo!", "I'm in Mexico City!");
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
//
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
//
public void onLocationChanged(Location location) {
lat = (int) (location.getLatitude()* 1E6);
lng = (int) (location.getLongitude()* 1E6);
// latituteField.setText(String.valueOf(lat));
// longitudeField.setText(String.valueOf(lng));
}
//
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
//
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
//
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
The right code is this ,but also add uses-permissio ,Internet,ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION and WRITE_EXTERNAL_STORAGE .user-library .
public class GoogleMapActivity extends MapActivity implements LocationListener {
private final static String TAG = GoogleMapActivity.class.getSimpleName();
private MyItemizedOverlay itemizedOverlay;
double lat;
double lng;
private String provider;
private LocationManager locationManager;
private MapView mapview;
Drawable drawable;
boolean sat = true;
boolean dra = true;
private MapController controller;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// fetch the map view from the layout
mapview = (MapView) findViewById(R.id.mapview);
// make available zoom controls
mapview.setBuiltInZoomControls(false);
// Use the location manager through GPS
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
lat = (double) (location.getLatitude());
lng = (double) (location.getLongitude());
Log.i(TAG, "Lattitude:" + lat);
Log.i(TAG, "Longitude:" + lng);
Toast.makeText(
this,
"Current location:\nLatitude: " + lat + "\n"
+ "Longitude: " + lng, Toast.LENGTH_LONG).show();
// create geo point
GeoPoint point = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
// get the MapController object
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();
drawable = this.getResources().getDrawable(R.drawable.ic_launcher);
OverlayItem overlayItem = new OverlayItem(point, "", "");
itemizedOverlay = new MyItemizedOverlay(drawable, this);
itemizedOverlay.addOverlay(overlayItem);
mapview.getOverlays().add(itemizedOverlay);
mapview.invalidate();
} else {
System.out.println("Location not avilable");
}
// when the current location is found – stop listening for updates
// (preserves battery)
locationManager.removeUpdates(this);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
#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);
}
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onLocationChanged(Location location) {
}
public MapView getMapView() {
return this.mapview;
}
}
` //here is another of item overlay
public class MyItemizedOverlay extends ItemizedOverlay<OverlayItem>
{
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
public MyItemizedOverlay(Drawable defaultMarker, Context ctx){
super(boundCenterBottom(defaultMarker));
}
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
populate();
}
public void clear() {
mOverlays.clear();
populate();
}
#Override
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
#Override
public int size() {
return mOverlays.size();
}
#Override
protected boolean onTap(int index) {
return true;
}
}
I would recommend MyLocationOverlay.
An Overlay for drawing the user's current location (and accuracy) on the map, and/or a compass-rose inset. Subclases can override dispatchTap() to handle taps on the current location.
You will want to call enableMyLocation() and/or enableCompass(), probably from your Activity's Activity.onResume() method, to enable the features of this overlay. Remember to call the corresponding disableMyLocation() and/or disableCompass() in your Activity's Activity.onPause() method to turn off updates when in the background.
Optionally, the constructor can also take a MapController and use it to keep the "my location" dot visible by panning the map when it would go offscreen, and a View to View.postInvalidate() when location or orientation is changed.
Runnables can be provided in runOnFirstFix(java.lang.Runnable) to be run as soon as we have a fix. (For example, this could center the map and zoom in to show the location.)
You can find a good tutorial on MyLocationOverlay here

mock location in android

I am using the following to mock my location in Android.
public class GPSwork extends Activity implements LocationListener{
LocationManager locationManager;
String mocLocationProvider;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mocLocationProvider = LocationManager.GPS_PROVIDER;
setLocation(28.574853,78.063201);
}
public void setLocation(double latitude, double longitude) {
locationManager.addTestProvider(mocLocationProvider, false, true, false, false, false, false, false, 0, 5);
locationManager.setTestProviderEnabled(mocLocationProvider, true);
locationManager.requestLocationUpdates(mocLocationProvider, 0, 0, this);
Location loc = new Location(mocLocationProvider);
loc.setTime(System.currentTimeMillis());
loc.setLatitude(latitude);
loc.setLongitude(longitude);
locationManager.setTestProviderLocation(mocLocationProvider, loc);
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
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
}
}
But it's not working. I want to see it in real device and the bubble blinking in that location, but I didnt get anything. Please correct my code, and help me out. I used the permissions.
I want build an application similatiom to location spoofer.Actually when we open google maps it will show our current location with blue blinking at our location..similarly if i changed the coordinates i.e, latitude and latitude it has to show that am at that location with blue blinking,
![alt text][1]
this is the screen short..
My XML fine is
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.maps.MapView
android:id="#+id/mapView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:apiKey="0Sy8vgJlQkFxcisUAkrxu3xN33dqFgBetCg4jxg"
/>
This is a basic pattern for an app that uses google maps:
public class MapsActivity extends MapActivity
{
MapView mapView;
MapController mc;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mapView = (MapView)findViewById(R.id.mapView);
//zoom controlls
mc = mapView.getController();
mc.setZoom(12);
setContentView(R.layout.main);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
}
In your AndroidManifest.xml file add:
<uses-library android:name="com.google.android.maps" />
and:
<uses-permission android:name="android.permission.INTERNET" />
To display your particular location add this to the onCreate method:
String coordinates[] = {"1.352566007", "103.78921587"};
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);
p = new GeoPoint(
(int) (lat * 1E6),
(int) (lng * 1E6));
mc.animateTo(p);
mc.setZoom(17);
mapView.invalidate();
Finally you need to set your marker using a map overlay. Add the following class to your MapsActivity class:
class MapOverlay extends com.google.android.maps.Overlay
{
#Override
public boolean draw(Canvas canvas, MapView mapView,
boolean shadow, long when)
{
super.draw(canvas, mapView, shadow);
//---translate the GeoPoint to screen pixels---
Point screenPts = new Point();
mapView.getProjection().toPixels(p, screenPts);
//---add the marker---
Bitmap bmp = BitmapFactory.decodeResource(
getResources(), R.drawable.my_bubble);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);
return true;
}
}
In this draw method you can to some marker animation if you want to. Now you have to add the overlay to your map:
//---Add a location marker---
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
This is a quick overview. You will need a google api key to work with google maps api. A detailed tutorial on google maps api can be found here, Using Google Maps in Android
Here is how to handle gps in android. It is a bad solution to make your main activity listen to location updates. Use and modify the following class:
public MyGPS implements LocationListener{
public LocationManager lm = null;
private MainActivity SystemService = null;
//lat, lng
private double mLongitude = 0;
private double mLatitude = 0;
public MyGPS(MainActivity sservice){
this.SystemService = sservice;
this.startLocationService();
}
public void startLocationService(){
this.lm = (LocationManager) this.SystemService.getSystemService(Context.LOCATION_SERVICE);
this.lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 5, this);
}
public void onLocationChanged(Location location) {
location = this.lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
try {
this.mLongitude = location.getLongitude();
this.mLatitude = location.getLatitude();
} catch (NullPointerException e) {
Log.i("Null pointer exception " + mLongitude + "," + mLatitude, null);
}
}
}
In your onCreate method make an instance of this class and the locationlistener will start to listen for gps updates. But you can not access lng and lat since you do not know from your activity wheather they are set or null. So you need a handler that sends a message to your main activity:
Modify in the following method:
public void onLocationChanged(Location location) {
location = this.lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
try {
this.mLongitude = location.getLongitude();
this.mLatitude = location.getLatitude();
Message msg = Message.obtain();
msg.what = UPDATE_LOCATION;
this.SystemService.myViewUpdateHandler.sendMessage(msg);
} catch (NullPointerException e) {
Log.i("Null pointer exception " + mLongitude + "," + mLatitude, null);
}
}
In your main activity add this:
Handler myViewUpdateHandler = new Handler(){
public void handleMessage(Message msg) {
switch (msg.what) {
case UPDATE_LOCATION:
//access lat and lng
}));
}
super.handleMessage(msg);
}
};
I think you have to extend the MyLocationOverlay class and Override the onDraw and change the location to your desired location and then call the superclass.onDraw method.

Categories

Resources