You are currently browsing the tag archive for the ‘gps location’ tag.

To get going with this tutorial one needs to go through all the previous 3 parts because we are using the same code from the previous tutorials and taking it a few steps further.

  1. https://mirnauman.wordpress.com/2012/01/30/using-google-maps-in-android-development-tutorial-part-1/
  2. https://mirnauman.wordpress.com/2012/02/07/using-gps-in-android-and-animating-google-maps-to-the-current-gps-location-android-tutorial-part-2/
  3. https://mirnauman.wordpress.com/2012/02/13/adding-image-to-googlemaps-using-map-overlays-android-tutorial-part-3/

Our main emphasis in this tutorial will be on adding a Menu to our Android GoogleMaps project and perform different actions using the buttons of that menu. So wat we will do is to create a menu with 3 buttons. Just like the one shown in the image below.

  1. My Current Location Button
  2. Map Satellite View Button
  3. Map Normal View Button

Menu with 3 buttons

Before we start we will copy 3 images(mylocation.png,satelliteview.png,normalview.png) in the drawables folder in the res folder. After this we will create a new xml file in the layout folder. We will name our file as “menu.xml”. The code for menu.xml is given below.

Menu XML file.

Save the menu.xml file and open GooglemapsActivity.java file. Now add the following code after the onCreate method in the GooglemapsActivity Class.

// Initiating Menu XML file (menu.xml)
 @Override
 public boolean onCreateOptionsMenu(Menu menu)
 {
 MenuInflater menuInflater = getMenuInflater();
 menuInflater.inflate(R.layout.menu, menu);
 return true;
 }

 /**
 * Event Handling for Individual menu item selected
 * Identify single menu item by it's id
 * */
 @SuppressWarnings("deprecation")
 @Override
 public boolean onOptionsItemSelected(MenuItem item)
 {

 switch (item.getItemId())
 {
 case R.id.my_location:
 // Single menu item is selected do something
 Toast.makeText(GooglemapsActivity.this, "Moving To Current location", Toast.LENGTH_SHORT).show();
 locLstnr.gpsCurrentLocation();

 return true;

 case R.id.mapview_normal:
 Toast.makeText(GooglemapsActivity.this, "Map Normal Street View", Toast.LENGTH_SHORT).show();
 if(mapView.isSatellite()==true){
 mapView.setSatellite(false);
 }
 return true;

 case R.id.mapview_satellite:
 Toast.makeText(GooglemapsActivity.this, "Map Satellite View", Toast.LENGTH_SHORT).show();
 if(mapView.isSatellite()==false){
 mapView.setSatellite(true);
 }
 return true;

 default:
 return super.onOptionsItemSelected(item);
 }
 }

In the above code, i have used locLstnr.gpsCurrentLocation(). To follow this completely one has to go through all the 3 previous parts of this tutorial. I have created a user defined function by the name of gpsCurrentLocation inside MyLocationListener Class. In this function I am getting the current coordinates and animating the map to that location. In the above code I have used the menu button to initiate this function. Now when we click the “My Location” button, the map will be animated to the current location, if we click the “Satellite View” button the map will be converted to satellite view and if we click the “Normal View” button than the map will be converted to Normal View.
Run and test the project and it will give us the following out put.

My Location Button Clicked and the map animated to current location

Satellite View Button Clicked and the map converted to Satellite View

Normal View Button Clicked and if the map is not is normal view it will be converted to normal view.

Now coming to the zooming functionality. All we need is just one line of code in the GooglemapsActivity Class. Add the following line after mapView = (MapView) findViewById(R.id.mapview1); in the onCreate method of our main GooglemapsActivity Class.


mapView.setBuiltInZoomControls(true);

Run the project and click on the map, click is must. As soon as the map is clicked the zooming controls will appear on the map.

Zoom Controls Enabled

Complete Source of MyLocationListener Class

 public class MyLocationListener implements LocationListener
 {

 @Override
 public void onLocationChanged(Location loc)
 {
 loc.getLatitude();
 loc.getLongitude();
 String Text = "My current location is: " +
 "Latitud = " + loc.getLatitude() +
 "Longitud = " + loc.getLongitude();
 Toast.makeText( getApplicationContext(),
 Text,
 Toast.LENGTH_SHORT).show();

 tvlat.setText(""+loc.getLatitude());
 tvlong.setText(""+loc.getLongitude());

 this.gpsCurrentLocation();
 }

 public void gpsCurrentLocation()
 {
 String coordinates[] = {""+tvlat.getText(), ""+tvlong.getText()};

 double lat = Double.parseDouble(coordinates[0]);
 double lng = Double.parseDouble(coordinates[1]);

 GeoPoint p = new GeoPoint(
 (int) (lat * 1E6),
 (int) (lng * 1E6));

mc.animateTo(p);
 mc.setZoom(7);

 MyMapOverlays marker = new MyMapOverlays(p) ;
 List listOfOverLays = mapView.getOverlays();
 listOfOverLays.clear();
 listOfOverLays.add(marker);

 mapView.invalidate();

 }

 @Override
 public void onProviderDisabled(String provider)
 {
 Toast.makeText( getApplicationContext(),
 "Gps Disabled",
 Toast.LENGTH_SHORT ).show();
 }

 @Override
 public void onProviderEnabled(String provider)
 {
 Toast.makeText( getApplicationContext(),
 "Gps Enabled",
 Toast.LENGTH_SHORT).show();
 }

 @Override
 public void onStatusChanged(String provider, int status, Bundle extras)
 {

 }

 }

Complete code of GooglemapsActivity Class

public class GooglemapsActivity extends MapActivity {

 private MapView mapView;
 private MapController mc;
 private TextView tvlat;
 private TextView tvlong;
 LocationManager locMgr;
 MyLocationListener locLstnr;
 Location mloc;

 /** Called when the activity is first created.
 * @return */

 @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);

 mapView = (MapView) findViewById(R.id.mapview1);
 mc = mapView.getController();
 mapView.setBuiltInZoomControls(true);

 tvlat = (TextView)findViewById(R.id.tv_lat);
 tvlong = (TextView)findViewById(R.id.tv_long);

 tvlat.setText("0");
 tvlong.setText("0 ");

 locMgr = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
 locLstnr = new MyLocationListener();

 locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locLstnr);

 }

 // Initiating Menu XML file (menu.xml)
 @Override
 public boolean onCreateOptionsMenu(Menu menu)
 {
 MenuInflater menuInflater = getMenuInflater();
 menuInflater.inflate(R.layout.menu, menu);
 return true;
 }

 /**
 * Event Handling for Individual menu item selected
 * Identify single menu item by it's id
 * */
 @SuppressWarnings("deprecation")
 @Override
 public boolean onOptionsItemSelected(MenuItem item)
 {

 switch (item.getItemId())
 {
 case R.id.my_location:
 // Single menu item is selected do something
 Toast.makeText(GooglemapsActivity.this, "Moving To Current location", Toast.LENGTH_SHORT).show();
 locLstnr.gpsCurrentLocation();

 return true;

 case R.id.mapview_normal:
 Toast.makeText(GooglemapsActivity.this, "Map Normal Street View", Toast.LENGTH_SHORT).show();
 if(mapView.isSatellite()==true){
 mapView.setSatellite(false);
 }
 return true;

 case R.id.mapview_satallite:
 Toast.makeText(GooglemapsActivity.this, "Map Satallite View", Toast.LENGTH_SHORT).show();
 if(mapView.isSatellite()==false){
 mapView.setSatellite(true);
 }
 return true;

  default:
 return super.onOptionsItemSelected(item);
 }
 }

}

Note:- Please leave your comments if this article was helpful.

Update # 1:- In response to Max Comment # 1:-

Dear Max,
ur confusion is right coz i have slightly changed the logic in the MyLocationListener Class and have not posted the Updated code.. The target was to click a button and move to the current location of the GPS. But it was not that simple. So here is wat i did.
In the onLocationChanged() method in MyLocationListener Class i assigned the Latitude and Longitude to two hidden textviews.

public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
String Text = “My current location is: ” +
“Latitud = ” + loc.getLatitude() +
“Longitud = ” + loc.getLongitude();
Toast.makeText( getApplicationContext(),
Text,
Toast.LENGTH_SHORT).show();

tvlat.setText(“”+loc.getLatitude());
tvlong.setText(“”+loc.getLongitude());
}

Than i created a new method inside MyLocationListener Class i.e, gpsCurrentLocation(). In gpsCurrentLocation() method i have used the code to get the coordinates from the textviews and animate the map to that location.

public void gpsCurrentLocation()
{
String coordinates[] = {“”+tvlat.getText(), “”+tvlong.getText()};

double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);

GeoPoint p = new GeoPoint(
(int) (lat * 1E6),
(int) (lng * 1E6));

mc.animateTo(p);
mc.setZoom(7);

MyMapOverlays marker = new MyMapOverlays(p) ;
List listOfOverLays = mapView.getOverlays();
listOfOverLays.clear();
listOfOverLays.add(marker);

mapView.invalidate();
}

After this call the gpsCurrentLocation() method in the OnLocationChanged() too . so that the method becomes like this


public class MyLocationListener implements LocationListener
{
@Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
String Text = “My current location is: ” +
“Latitud = ” + loc.getLatitude() +
“Longitud = ” + loc.getLongitude();
Toast.makeText( getApplicationContext(),
Text,
Toast.LENGTH_SHORT).show();

tvlat.setText(“”+loc.getLatitude());
tvlong.setText(“”+loc.getLongitude());

this.gpsCurrentLocation();
}

Now come to the code of ur button click, or in my case menu click.
Create an object of MyLocationListener Class.
and simply call the the gpsCurrentLocation() method through that object. and u will be able to animate the map to the current GPS coordinates.
MyLocationListener locLstnr = new MyLocationListener();
locLstnr.gpsCurrentLocation();

Plz leave ur comments if this solves the issue of animating the map to the current GPS coordinates on button click or menu click.

 

Update # 2: In response to Sagar Zade issue.

LinearLayout Tag Code.

LinearLayout Tag Code.

Objective of this tutorial is to place an image to the current location of the device, means displaying an image at the current coordinates from the GPS of the device. We can have a better idea from the image displayed below of what we are trying to achieve.

A Cross image added to the current location from the GPS of the device

To start with this tutorial we will continue with the examples  from the previous tutorial and to have the exact output one must go through the previous tutorials in this series i.e,

First of all we will create a PNG image with transparent background or download it from Google or search it in the android samples folders. When we have our desired image just like the one shown below.

Our PNG

Copy this PNG and browse to your “res” folder of the GoogleMaps project. My path for the “res” folder is “C:\Users\Mir Nauman Tahir\workspace\googlemaps\res\” . In “res” folder we will have 3 more folders starting from drawable i.e

  1. drawable-hdpi
  2. drawable-ldpi
  3. drawable-mdpi

we have to copy our image in the the drawable folder but which one. If you have no idea copy the image to all the three folders. By default the image will be taken from the hdpi folder, if the image is not found by that name in the hdpi folder than the mdpi folder is searched. so we have to have our image in one of the two folders.  If the same image is present in both the folders than the hdpi image is taken.

The reason behind putting our image in the “res” folder is that we can easily access our image file by “R.id.our_image” code. extension should not be entered. Using this method saves us a lot of overhead by not getting involved in the path to the file and the addressing schemes whether relative or absolute.

Now coming to the code. First we will create our own Map Overlay Class that will extend com.google.android.maps.Overlay. For the time being the Class should be defined inside our main GooglemapsActivity Class. The code is given below.

/*My overlay Class starts*/
 class MyMapOverlays extends com.google.android.maps.Overlay
 {
 GeoPoint location = null;

public MyMapOverlays(GeoPoint location)
 {
 super();
 this.location = location;
 }

@Override
 public void draw(Canvas canvas, MapView mapView, boolean shadow)
 {

 super.draw(canvas, mapView, shadow);
 //translate the screen pixels
 Point screenPoint = new Point();
 mapView.getProjection().toPixels(this.location, screenPoint);

 //add the image
 canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.our_cross_image),
 screenPoint.x, screenPoint.y , null); //Setting the image  location on the screen (x,y).
 }
 }
 /*My overlay Class ends*/

We have our main map Overlay class in place, now we will come to our MyLocationListener Class. This is not necessary here. The following code can also be defined in onCreate method of our main GooglemapsActivity Class but as we want to draw the image on the current location of the GPS and that if the GPS coordinates changes the image should reapear in the newly updated location we will add this code to MyLocationListener Class.

Add the following code in the “onLocationChanged(Location loc)”  between “mc.setZoom(7)” and mapView.invalidate(). From our previous tutorial code https://mirnauman.wordpress.com/2012/02/07/using-gps-in-android-and-animating-google-maps-to-the-current-gps-location-android-tutorial-part-2/

//add a location marker.

 MyMapOverlays marker = new MyMapOverlays(p) ;
 List listOfOverLays = mapView.getOverlays();
 listOfOverLays.clear();
 listOfOverLays.add(marker);

 mapView.invalidate();

mapView.invalidate() should be the last statement coz it will redraw the map. Now Run the project. When the map loads for the first time it will show no image. At this stage send dummy coordinates from the DDMS and the map will animate to the current coordinates receieved from the DDMS and will show our “Cross” image on the current location.

Sending dummy coordinates from DDMS, Map animated to the current location and displaying our "Cross" image at the current location

This was all for adding images using map overlays. We will extend the same tutorial series for exploring further functionalities of GoogleMaps.

Note:- Please leave your comments if this article was of any help. Thanks.

Blog Stats

  • 329,162 hits

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 233 other followers

%d bloggers like this: