I have a mapview page that displays the current location in the map.
I am using MyLocationOverlay for the purpose. The code for that goes as follows:
myLocationOverlay = new MyLocationOverlay(this, mapView);
myLocationOverlay.enableCompass();
myLocationOverlay.enableMyLocation();
myLocationOverlay.runOnFirstFix(new Runnable() {
public void run() {
geopoint = myLocationOverlay.getMyLocation();
ItemizedOverlay itemizedoverlay = new ItemizedOverlay(drawable);
try{
overlayitem = new OverlayItem(geopoint, "", "");
}
catch(Exception e){
e.printStackTrace();
}
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
mapController.animateTo(geoPoint);
}
});
The above code works and gets the current location through gps and sets a marker at that point.
But the code inside try block is the issue.
I am getting null value inside geopoint.
Actually I have to get that point and do some calculations with distance and all. For that I have to get the correct value inside that geopoint.
Can anyone please tell the solution for this?
I've been working on the same problem for a day now and here's what I've discovered. For some reason this works
LocationManager lm;
GeoPoint gp;
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location lastKnownLoc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastKnownLoc != null){
int longTemp = (int)(lastKnownLoc.getLongitude()* 1000000);
int latTemp = (int)(lastKnownLoc.getLatitude() * 1000000);
gp = new GeoPoint(latTemp, longTemp);
}
and this doesn't
gp = myLocOverlay.getMyLocation();
Tracking current location can be done by using MyLocationOverlay class and through LocationManager. Using MyLocationOverlay, the code below works..
MyLocationOverlay myLocationOverlay;
MapView mapView;
MapController mapcontroller;
OverlayItem overlayitem;
List<Overlay> mapoverlays;
GeoPoint geopoint;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.currentlocation);
mapView = (MapView) findViewById(R.id.map);
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(false);
mapView.setStreetView(true);
mapView.setTraffic(true);
mapcontroller = mapView.getController();
mapoverlays = mapView.getOverlays();
drawable = this.getResources().getDrawable(R.drawable.ic_map_red);
mapView.invalidate();
getCurrentLocation();
}
public void getCurrentLocation(){
myLocationOverlay = new MyLocationOverlay(this, mapView);
myLocationOverlay.enableCompass();
myLocationOverlay.enableMyLocation();
myLocationOverlay.runOnFirstFix(new Runnable() {
public void run() {
ItemizedOverlay itemizedoverlay = new ItemizedOverlay(drawable);
try {
latitude = myLocationOverlay.getMyLocation().getLatitudeE6();
longitude = myLocationOverlay.getMyLocation().getLongitudeE6();
geopoint = new GeoPoint((int) (latitude), (int) (longitude));
overlayitem = new OverlayItem(geopoint, "", "");
itemizedoverlay.addOverlay(overlayitem);
mapoverlays.add(itemizedoverlay);
mapcontroller.animateTo(geopoint);
mapcontroller.setZoom(16);
}
catch (Exception e) {}
}
});
}
If you override:
onLocationChanged();
Remember to call:
super.onLocationChanged();
after or before your own code. This appears to ensure that the variable
getMyLocation()
returns is not null.
The friend upstairs made me rise that try override nothing, neither draw nor drawMyLocation.
Just like this:
MyLocationOverlay myLocationOverlay = new SelfLocationOverlay(this, mapView);
myLocationOverlay.enableMyLocation();
myLocationOverlay.disableCompass();
mapView.getOverlays().add(myLocationOverlay);
Related
I am trying to buid a simple app that when user enter his desired location its map appear.But i am getting an error Cannot instantiate the type GeoPoint i have also installed Google Play Services.
here is the code :
public class MainActivity extends MapActivity {
EditText location;
Geocoder geoCoder;
GeoPoint p;
MapController controller;
MapView mapView;
Button btnSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
location=(EditText)findViewById(R.id.txtAddress);
mapView = (MapView) findViewById(R.id.mapView);
btnSearch.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
List<Address> addresses;
try {
addresses = geoCoder.getFromLocationName(location.getText().toString(),1);
if(addresses.size() > 0)
{
p = new GeoPoint( (int) (addresses.get(0).getLatitude() * 1E6),
(int) (addresses.get(0).getLongitude() * 1E6));
controller.animateTo(p);
controller.setZoom(12);
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
location.setText("");
}
else
{
AlertDialog.Builder adb = new AlertDialog.Builder(MainActivity.this);
adb.setTitle("Google Map");
adb.setMessage("Please Provide the Proper Place");
adb.setPositiveButton("Close",null);
adb.show();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
Is there a particular reason you need to use v1 of the Google maps api, instead of the current v2? If not, try using LatLng to store the location, and map.moveCamera(LatLng, float zoom) to go to the desired location as shown here.
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();
One part of the application I am making requires google map. I want the user to be able to type into edittext some search string and then press a search button and the map will animate to the first result.
When I press the button the application searches and takes the first result and puts it into a geopoint, so that part of the program is working. But when I try to animate to that point the application crashes.
Here is the onCreate function where I successfully navigate to the location "Dalvík, Iceland".
public class LocationPicker extends MapActivity {
static GeoPoint point;
static MapController mc;
static MapView mapView;
private EditText location;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_picker);
MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
location = (EditText)findViewById(R.id.locationString);
mc = mapView.getController();
String tmp = "Dalvík, Iceland";
try {
point = searchLocation(tmp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mc.animateTo(point);
mc.setZoom(14);
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
}
And my code for the button click is, and to be clear the System.out.println(point) prints valid point. But still when I click the button my application crashes.
public void search(View v) throws IOException{
GeoPoint tmpPoint = searchLocation(location.getText().toString());
System.out.println(tmpPoint);
if( tmpPoint != null){
mc.animateTo(tmpPoint);
mapView.invalidate();
}
}
And the searchLocation functions is as follows:
public GeoPoint searchLocation (String searchString) throws IOException{
Geocoder geo = new Geocoder(this);
List<Address> addr;
addr = geo.getFromLocationName(searchString, 10);
if(!addr.isEmpty()){
Address loc = addr.get(0);
GeoPoint point = new GeoPoint((int) (loc.getLatitude() * 1E6),
(int) (loc.getLongitude() * 1E6));
return point;
}
else {
return null;
}
}
So to summerize I am clearly doing something wrong in the onclick "search" function.
Any ideas what is wrong?
You are not checking the right variable for null value:
if( point != null){
mc.animateTo(tmpPoint);
mapView.invalidate();
}
should be
if( tmpPoint!= null){
mc.animateTo(tmpPoint);
mapView.invalidate();
}
Additionnally, you want to make the call to the geoCoder.getFromLocationName method outside the UI thread as this can be time consumming. Use an AsyncTask for that for instance.
Finally, even if you get a list of addresses, they are not guaranted to have latitude and longitude. Use the hasLatitude and hasLongitude functions to pick the first address of the result list with coordinates.
I found the answer.
The problem causing this was this line
mapView.invalidate();
Hear is my project
In my project I am showing my current location,showing the current lat-long.But I'm not able
to mark my current position in android.
Thnx in advance.
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.d(TAG, "onLocationChanged with location " + location.toString());
// Displays lat, long, altitude and bearing
String text = String.format("Lat:\t %f\nLong:\t %f\nAlt:\t %f\nBearing:\t %f", location.getLatitude(), location.getLongitude(), location.getAltitude(), location.getBearing());
this.locationText.setText(text);
try {
// This gets a list of addresses
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(),
location.getLongitude(), 10);
for (Address address : addresses) {
this.locationText.append("\n" + "kaushik");
}
// Convert latitude and longitude into int that the GeoPoint constructor can understand
int latitude = (int)(location.getLatitude() * 1000000);
int longitude = (int)(location.getLongitude() * 1000000);
point = new GeoPoint(latitude,longitude);
mapController.animateTo(point);
mapController.setZoom(16);
MapOverlay mapOverLay=new MapOverlay();
mapOverLay.setPointToDraw(point);
List<Overlay> listOfOverlays=map.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverLay);
map.invalidate();
} catch (IOException e) {
Log.e("LocateMe", "Could not get Geocoder data", e);
}
}
mapController.animateTo(point);
mapController.setZoom(16);
MapOverlay mapOverLay=new MapOverlay();
mapOverLay.setPointToDraw(point);
List<Overlay> listOfOverlays=map.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverLay);
Replace the above lines with below lines//where lat and long are fetched from gps.
Drawable srcdrawable = getApplicationContext().getResources().getDrawable(R.drawable.pin_blue);
CustomItemizedOverlay srcitemizedOverlay = new CustomItemizedOverlay(srcdrawable, getApplicationContext());
GeoPoint srcpoint = new GeoPoint((int)( Double.parseDouble(lat) * 1E6),(int)( Double.parseDouble(lng)* 1E6));
OverlayItem srcoverlayitem = new OverlayItem(srcpoint, "Hello!", "This is your Location.");
srcitemizedOverlay.addOverlay(srcoverlayitem);
mapView.getOverlays().clear();
mapView.getOverlays().add(srcitemizedOverlay);
mapController.animateTo(srcpoint);
mapController.setZoom(16);
//If you want more than one point on map
/*
Drawable srcdrawable = getApplicationContext().getResources().getDrawable(R.drawable.pin_blue);
CustomItemizedOverlay srcitemizedOverlay = new CustomItemizedOverlay(srcdrawable, getApplicationContext());
forloop(setoflocations){
GeoPoint srcpoint = new GeoPoint((int)( Double.parseDouble(lat) * 1E6),(int)( Double.parseDouble(lng)* 1E6));
OverlayItem srcoverlayitem = new OverlayItem(srcpoint, "Hello!", "This is your Location.");
if(srcitemizedOverlay!=null && mapController!=null){
srcitemizedOverlay.addOverlay(overlayitem);
mapController.animateTo(point);
animatePoint = point;
}
}
mapView.getOverlays().clear();
mapView.getOverlays().add(srcitemizedOverlay);
*/
also use the below CustomItemizedOverlay.java class
public class CustomItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private final ArrayList<OverlayItem> mapOverlays = new ArrayList<OverlayItem>();
private Context context;
public CustomItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
public CustomItemizedOverlay(Drawable defaultMarker, Context context) {
this(defaultMarker);
this.context = context;
}
#Override
protected OverlayItem createItem(int i) {
return mapOverlays.get(i);
}
#Override
public int size() {
return mapOverlays.size();
}
public void addOverlay(OverlayItem overlay) {
mapOverlays.add(overlay);
this.populate();
}
}
add overlay Icon on current location
myItemizedOverlay.addItem(point , "myPoint1", "myPoint1");
m_mapView.getOverlays().add(myItemizedOverlay);
mapController.animateTo(point);
I have the following code ...
HERE the variable point is a Geopoint object .
I need the current GPS location of my Android , to be updated on this point...
What do I call ? to define the current location on POINT ?!
// create a map view
RelativeLayout linearLayout = (RelativeLayout) findViewById(R.id.mainlayout);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapView.setStreetView(true);
mapController = mapView.getController();
mapController.setZoom(14); // Zoom 1 is world view
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,0, new GeoUpdateHandler());
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.androidmarker);
HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable);
OverlayItem overlayitem = new OverlayItem(point, "Hola, people!", "I am on Earth");
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
public class GeoUpdateHandler implements LocationListener {
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude() * 1E6);
int lng = (int) (location.getLongitude() * 1E6);
GeoPoint point = new GeoPoint(lat, lng);
mapController.animateTo(point);
//mapController.setCenter(point);
}
Take the look the following class
http://code.google.com/android/add-ons/google-apis/reference/com/google/android/maps/MyLocationOverlay.html
You could just use this class to display user's current location on the map.