You are currently browsing the tag archive for the ‘Android Google Maps API Ver 1.0’ tag.

To get going with this tutorial I am using the code from my previous tutorial https://mirnauman.wordpress.com/2012/04/10/android-google-maps-tutorial-part-5-adding-multiple-images-to-google-maps-using-itemizedoverlay/

Objective:-

To get the Latitude and Longitude values of a location that is touched on Google Maps in Android.

Solution:-

All we need is a simple function onTouchEvent(MotionEvent event, MapView mapView), that can be added to either a Class that extends Overlay  or a Class that extends ItemizedOverlay. In my tutorial I have used ItemizedOverlay so I ll add the function to my class “MirItemizedOverlay” that extends ItemizedOverlay.

Function to be added:-


@Override
 public boolean onTouchEvent(MotionEvent event, MapView mapView)
 {
 //---when user lifts his finger---
 if (event.getAction() == 1) {
 GeoPoint p = mapView.getProjection().fromPixels(
 (int) event.getX(),
 (int) event.getY());
 Toast.makeText(getBaseContext(),
 p.getLatitudeE6() / 1E6 + "," +
 p.getLongitudeE6() /1E6 ,
 Toast.LENGTH_SHORT).show();
 }
 return false;
 }

Now when we Run the Application and touch the sceen. As soon as we lift the touch, the application will display the Latitude and Longitude values in a Toast.

Latitude and Longitude of the location that is touched on the Map.

Complete code of tutorial Google Maps Part 5 will become


package com.android.googlemapsapp;

import java.util.ArrayList;
 import java.util.List;

import android.app.Activity;
 import android.graphics.drawable.Drawable;
 import android.os.Bundle;
 import com.google.android.maps.GeoPoint;
 import com.google.android.maps.ItemizedOverlay;
 import com.google.android.maps.MapActivity;
 import com.google.android.maps.MapController;
 import com.google.android.maps.MapView;
 import com.google.android.maps.MyLocationOverlay;
 import com.google.android.maps.OverlayItem;

import android.os.Bundle;
 import android.view.MotionEvent;
 import android.widget.Toast;

public class GoogleMapsAppActivity extends MapActivity {

private MapView mapView;
 private MapController mc;
 //MyLocationOverlay myLocOverlay = null;

/** Called when the activity is first created. */
 @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);

Drawable makerDefault = this.getResources().getDrawable(R.drawable.star_big_on);
 MirItemizedOverlay itemizedOverlay = new MirItemizedOverlay(makerDefault);
 GeoPoint point = new GeoPoint(33480000, 73000000);

OverlayItem overlayItem = new OverlayItem(point, "Islamabad", null);
 itemizedOverlay.addOverlayItem(33695043, 73000000, "Islamabad");
 itemizedOverlay.addOverlayItem(33480000, 73000000, "Some Other Pakistani City");
 itemizedOverlay.addOverlayItem(33380000, 73000000, "Some Other Pakistani City");

mapView.getOverlays().add(itemizedOverlay);

MapController mc = mapView.getController();
 mc.setCenter(new GeoPoint(33580000, 73000000)); // Some where near Islamabad.
 mc.zoomToSpan(itemizedOverlay.getLatSpanE6(), itemizedOverlay.getLonSpanE6());

}

@Override
 protected boolean isRouteDisplayed() {
 // TODO Auto-generated method stub
 return false;
 }

private class MirItemizedOverlay extends ItemizedOverlay<OverlayItem> {

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

public MirItemizedOverlay(Drawable defaultMarker) {
 super(boundCenterBottom(defaultMarker));
 // TODO Auto-generated constructor stub
 }
 @Override
 protected OverlayItem createItem(int i) {
 return mOverlays.get(i);
 }

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

public void addOverlayItem(OverlayItem overlayItem) {
 mOverlays.add(overlayItem);
 populate();
 }

public void addOverlayItem(int lat, int lon, String title) {
 GeoPoint point = new GeoPoint(lat, lon);
 OverlayItem overlayItem = new OverlayItem(point, title, null);
 addOverlayItem(overlayItem);
 }

@Override
 public boolean onTouchEvent(MotionEvent event, MapView mapView)
 {
 //---when user lifts his finger---
 if (event.getAction() == 1) {
 GeoPoint p = mapView.getProjection().fromPixels(
 (int) event.getX(),
 (int) event.getY());
 Toast.makeText(getBaseContext(),
 p.getLatitudeE6() / 1E6 + "," +
 p.getLongitudeE6() /1E6 ,
 Toast.LENGTH_SHORT).show();
 }
 return false;
 }

}

}

Advertisements

Dear readers am back after a long time trying to complete what i started a few months back. This article is part 5 of the previous series but it doesn’t depend on the code of the previous articles, still they can be referenced to get a better understanding of configuring Google Maps for Android and learning the basic development of Google Maps for Android. The development environment stays the same as of the previous articles. No change in any of the configurations etc.

Please see the links for previous articles for basics of Google Maps for Android.

  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/
  4. https://mirnauman.wordpress.com/2012/02/14/android-google-maps-tutorial-part-4-adding-menu-some-additional-functionality-like-zooming-changing-map-view-animating-to-gps-current-location-using-menu-button/

Objective of this article is to add multiple images to our Google Map Application for Android. I have taken a scenario where I have a list of coordinates  of different cities of Pakistan and I want display an image on each city. Check the final output of this article so that you have an idea of what we will achieve at the end of this tutorial.

Multiple Images Displayed on our Android Google Maps Application.

Starting with the actual work,  inside the main GoogleMapsAppActivity Class that  extends MapActivity, add a Class lets say MirItemizedClass that extends ItemizedOverlay.  This is a  base class for an Overlay which consists of a list of OverlayItems. This handles sorting north-to-south for drawing, creating span bounds, drawing a marker for each point, and maintaining a focused item. It also matches screen-taps to items, and dispatches Focus-change events to an optional listener.


private class MirItemizedOverlay extends ItemizedOverlay {

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

 public MirItemizedOverlay(Drawable defaultMarker) {
 super(boundCenterBottom(defaultMarker));
 // TODO Auto-generated constructor stub
 }

 @Override
 protected OverlayItem createItem(int i) {
 return mOverlays.get(i);
 }

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

 public void addOverlayItem(OverlayItem overlayItem) {
 mOverlays.add(overlayItem);
 populate();
 }

 }

We have to set the bounding rectangle of the drawable  that we add to our ItemizedOverlay. The defaultMarker is a Drawable that is drawn on every OverlayItem that we add to our ItemizedOverlay. To do this we have to use boundCenterBottom or boundCenter or we can use the setBounds method to get the job done. So we have used boundCenterBottom(defaultMaker).  To add multiple overlays we have added a List of OverlayItem and used that in the createItem and size methods of our ItemizedOverlay Class. To add the OverlayItems to our internal list we have added the method addOverlayItem(OverlayItem overlayItem).

Now we will use the functionality of MirItemizedOverlay Class in the onCeate method of our main GoogleMapsAppActivity Class.

We will create instances of Drawable and MirItemizedOverlay to retrieve the image from our res/drawable folder and to supply that image to the our ItemizedOverlay Class.


Drawable makerDefault = this.getResources().getDrawable(R.drawable.star_big_on);
 MirItemizedOverlay itemizedOverlay = new MirItemizedOverlay(makerDefault);
 GeoPoint point = new GeoPoint(33480000, 73000000);

We have also ceated a GeoPoint object with a latitude, longitude value.  Add another method  to our MirItemizedOverlay Class that will take two integers and a string as parameters.


public void addOverlayItem(int lat, int lon, String title) {
 GeoPoint point = new GeoPoint(lat, lon);
 OverlayItem overlayItem = new OverlayItem(point, title, null);
 addOverlayItem(overlayItem);
 }

The code to create and add multiple locations to our itemizedOverlay object by using the recently created method is


OverlayItem overlayItem = new OverlayItem(point, "Islamabad", null);
 itemizedOverlay.addOverlayItem(33695043, 73000000, "Islamabad");
 itemizedOverlay.addOverlayItem(33480000, 73000000, "Some Other Pakistani City");
 itemizedOverlay.addOverlayItem(33380000, 73000000, "Some Other Pakistani City");

Now enable the mapView control to display the itemizedOverlay


mapView.getOverlays().add(itemizedOverlay);

Now tweek the mapView to get focused at a certain point and set the zooming level.


MapController mc = mapView.getController();
 mc.setCenter(new GeoPoint(33580000, 73000000)); // Some where near Islamabad.
 mc.zoomToSpan(itemizedOverlay.getLatSpanE6(), itemizedOverlay.getLonSpanE6());

Run the project we will get the output in the picture given above.

Complete Code of this tutorial.


package com.android.googlemapsapp;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;

import android.os.Bundle;

&nbsp;

public class GoogleMapsAppActivity extends MapActivity {

 private MapView mapView;
 private MapController mc;

 /** Called when the activity is first created. */
 @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);

 Drawable makerDefault = this.getResources().getDrawable(R.drawable.star_big_on);
 MirItemizedOverlay itemizedOverlay = new MirItemizedOverlay(makerDefault);
 GeoPoint point = new GeoPoint(33480000, 73000000);

 OverlayItem overlayItem = new OverlayItem(point, "Islamabad", null);
 itemizedOverlay.addOverlayItem(33695043, 73000000, "Islamabad");
 itemizedOverlay.addOverlayItem(33480000, 73000000, "Some Other Pakistani City");
 itemizedOverlay.addOverlayItem(33380000, 73000000, "Some Other Pakistani City");

 mapView.getOverlays().add(itemizedOverlay);

 MapController mc = mapView.getController();
 mc.setCenter(new GeoPoint(33580000, 73000000)); // Some where near Islamabad.
 mc.zoomToSpan(itemizedOverlay.getLatSpanE6(), itemizedOverlay.getLonSpanE6());

}

@Override
 protected boolean isRouteDisplayed() {
 // TODO Auto-generated method stub
 return false;
 }

 private class MirItemizedOverlay extends ItemizedOverlay {

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

 public MirItemizedOverlay(Drawable defaultMarker) {
 super(boundCenterBottom(defaultMarker));
 // TODO Auto-generated constructor stub
 }
 @Override
 protected OverlayItem createItem(int i) {
 return mOverlays.get(i);
 }

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

 public void addOverlayItem(OverlayItem overlayItem) {
 mOverlays.add(overlayItem);
 populate();
 }

 public void addOverlayItem(int lat, int lon, String title) {
 GeoPoint point = new GeoPoint(lat, lon);
 OverlayItem overlayItem = new OverlayItem(point, title, null);
 addOverlayItem(overlayItem);
 }
 }

}

The reason behind writing this article is that I got a new machine and I was configuring it for Android development. Everything went well but when came to the step for generating the Google Maps API Key, I got stuck when couldn’t find “debug.keystore” file at the desired location inside “.android”  folder.

.android folder without debug.keystore file

If we don’t have debug.keystore file we can’t get Google Maps API Key. To solve this issue and to get the debug.keystore file in the desired location is

  1. Open Eclipse
  2. Start a new Android project
  3. Run the project in any AVD that’s already created.

When the project is successfully RUN on the Android Virtual Device. Now go to your “.android” folder and check. You will see that the “debug.keystore” is present there.

.android folder with debug.keystore

REASON

By default the “debug.keystore” file is not created in “.android” folder. When we successfully build our first project, the “debug.keystore” file is automatically created in “.android” folder.

Now we can use it to generate our Google Maps API Key.

Related Article

https://mirnauman.wordpress.com/2012/01/26/how-to-get-google-maps-api-key-for-android-issues-and-errors-solved/

 

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.

In this tutorial we will make our way to get Coordinates from GPS. We will use the emulator, will learn how to use the emulator and how to use the DDMS and how we can send coordinates from DDMS to our emulator. We will start with a very basic application that will get coordinates from the GPS and will display it in a Toast. In the second part of this tutorial we will use those coordinates and will make our Google Maps animate to that location automatically. For using Google Maps Basics follow the link

https://mirnauman.wordpress.com/2012/01/30/using-google-maps-in-android-development-tutorial-part-1/

We will continue with the code in the above example, using the same API and AVD. First of all add the following permission in the AndroidManifest.xml file, if its not been already added.

<uses-permission android:name="android.permission.INTERNET"/>
 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

Secondly check the AVD that is it with GPS support or not. As we can see in the hardware section that “GPS Support” has a yes infront of it. Means GPS Support is installed.

Creating & Configuring New AVD

There will be no change in the “main.xml” file. Now open the “GoogleMapsActivity.java” file. Add the following to the import section of the file. At the top.

import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;

Create a LocationManager and LocationListner objects in our main “GoogleMapsActivity” Class.

LocationManager locMgr;
 MyLocationListener locLstnr;

Now Create a whole new class by the name of MyLocationListner inside the GoogleMapsActivity 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();

 }

 @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)
 {

 }

 }

Now in the GoogleMapsActivity class add the following lines of code to create the LocationManager object and MyLocationListner object.

locMgr = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locLstnr = new MyLocationListener();
locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locLstnr);

Check the picture below. In the image below will have used DDMS to send dummy coordinates to our emulator. We have to keep a few points in mind when sending dummy coordinates to emulator.

Toast displaying our dummy coordinates sent from DDMS to our emulator.

First of all emulator should be select in the Devices Tab in the DDMS. In the above picture my device is shown as emulator-5554. Secondly while the device selected. Open the Emulator Control Tab, Inside that tab open the Manual Tab and scroll down to location controls. Now click send and you will see a toast appear on our emulator displaying our message including coordinates that we have just sent from DDMS. With this step our first phase of the tutorial is complete. To animate the GoogleMap to the location of the Coordinates that we have received. Add the following code in the onLocationChanged method of our MyLocationListner Class

String coordinates[] = {""+loc.getLatitude(), ""+loc.getLongitude()};
 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);
 mapView.invalidate();

Comment the code that displays the Toast and run the Project. Send dummy locations from DDMS and we will see that the Map will animate to the location of the coordinates that we have provided from DDMS.

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

Next tutorial on its way ( adding images to GoogleMaps, OverLays )

This tutorial is first of the detailed tutorial that am planning to write. Some short details about my development environment.

  • Windows 7 Professional
  • Android 2.3.3(API10)
  • Google APIs (Google Inc)-API Level 10. (Create AVD of this API)
  • Eclipse Classic version 3.7.0

Before we start with the development of our first Google Maps Application for Android. We need to get Google Maps Api Key. I have made it very simple to get the key. Follow the link.

https://mirnauman.wordpress.com/2012/01/26/how-to-get-google-maps-api-key-for-android-issues-and-errors-solved/

Perform all the steps in the above link and get the key. When we have the key than we will proceed will our development of Google Maps Application for Android.

Start a new Android Project, when prompted for SDK selection

SDK selection

Select Google APIs Platform 2.3.3 API level 10, and move next. When the project has been created. Open your MainActivity.java file. In my case I have named it GooglemapsActivity.java. Import the following.


import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;

Now change the line

public class GooglemapsActivity extends Activity {

to

public class GooglemapsActivity extends MapActivity {

Now open the main.xml file and add a MapView

<com.google.android.maps.<span class="hiddenSpellError">MapView
 android:id="@+id/mapview1"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:enabled="true"
 android:clickable="true"
 android:apiKey=""
 />


Save the changes. Now open the AndroidManifest.xml file and Add the following permissions above the application tag.

<uses-permission android:name="android.permission.INTERNET"/>
 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

Now add the google maps library in the manifest file, inside the application tag above the activity tag.

<uses-library android:name="com.google.android.maps"/>

Save the changes.  Now Open the Android Virtual Device Manager and create a new AVD with the following settings.

Creating & Configuring New AVD

We must provide GPS and SD Card support in the AVD because we will need these two functionalities for our future tutorials. Now Right click on our googlemaps application from the PackageExplorer and click Run Configuration from Run As menu. Now Create new configuration from the selecting our googlemaps application on the Android Tab.

Run Configuration For Our Android Project

Selected Target AVD

And Select our recently created AVD from the target Tab. Click Apply and Run. Everything is fine still the application will not load any map. Reason is that, we have not created an instance of our MapView in our main GooglemapsActivity Class. To do that. Add the following lines of code below the setContentView() line.

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

Save the changes and run the project again. Now everything is double fine but still the emulator will show empty grid like the one shown in the picture.

Google Maps Empty Grid

Reasons for this blank grid is that we have not supplied our application with the google maps api key. For this Open the main.xml file and replace the following code.

<com.google.android.maps.MapView
 android:id="@+id/mapview1"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:enabled="true"
 android:clickable="true"
 android:apiKey=""
 />

with

<com.google.android.maps.MapView
 android:id="@+id/mapview1"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:enabled="true"
 android:clickable="true"
 android:apiKey="xxxxxxxxxxxxxxxxxxxxxxxxxxx"
 />

The “xxxxxxxxxxxxxxxxxxxxxxx” show your Google Maps API Key that we have generated at the start of this tutorial. If the Google Maps API Key is correct than we will get a screen like this.

Default Map Location Loaded in the MapView Control

We can animate the map to a default location or to our desired coordinates. Add the following lines of code and the map will load at our desired coordinates and our desired zoom level.

String coordinates[] = {"30", "71"};
 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);
 mapView.invalidate();

Map animated to our desired location

We have provided latitude = 30 and longitude = 71, zooming level =7. The map will center at the provided coordinates at the provided zooming level. I may have forgotten to explain some details so i am attaching the complete code the 3 main files for this project.

GooglemapsActivity.java Complete code

package com.maptest.googlemap;

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 android.os.Bundle;

public class GooglemapsActivity extends MapActivity {

 private MapView mapView;
 private MapController mc;

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);

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

String coordinates[] = {"30", "71"};
 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);
 mapView.invalidate();
 }

@Override
 protected boolean isRouteDisplayed() {
 // TODO Auto-generated method stub
 return false;
 }
}

AndroidManifest.xml Complete Code

<?xml version="1.0" encoding="utf-8"?>
xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.maptest.googlemap"
 android:versionCode="1"
 android:versionName="1.0" >

<uses-sdk android:minSdkVersion="10" />
 <uses-permission android:name="android.permission.INTERNET"/>
 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

<application
 android:icon="@drawable/ic_launcher"
 android:label="@string/app_name" >

 <uses-library android:name="com.google.android.maps"/>

 <activity
 android:name=".GooglemapsActivity"
 android:label="@string/app_name" >
 <intent-filter>
 <action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
 </intent-filter>
 </activity>
 </application>

</manifest>

main.xml Complete Code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:orientation="vertical" >

<com.google.android.maps.MapView
 android:id="@+id/mapview1"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:enabled="true"
 android:clickable="true"
 android:apiKey="xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
 />

</LinearLayout>

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

Update # 1.

Addressing the issues in comments from harrison , hennie and topan. The problem with force cash is solved by the following :

replace ur mapview control code in main.xml with this

<com.google.android.maps.MapView
        android:id=”@+id/mapview1″
        android:layout_width=”fill_parent”
        android:layout_height=”322dp”
        android:layout_weight=”0.64″
        android:apiKey=”0VUxp2vFvlmp4w3BsQu-xxxxxxxxxxxxxxxxxxxxxxg”
        android:clickable=”true” >
    </com.google.android.maps.MapView>
if this doesnt work than check ur google maps api key.
The above solution worked for Harrison and his reply to me was
Mir!Thank you very much, you have gotten this to work for me! Thank you very much!The solution was:
<com.google.android.maps.MapView

>

    </com.google.android.maps.MapView>For some reason it is really strict about the format of com.google.android.maps.MapViewThank you very much! Your help is GREATLY appreciated and now I can resume working on my design project.Thanks again,

Harrison

Update # 2.
Issue in which maps is not shown on the phone, if only dark screen is shown than this can be solved by zooming out a few times. Zooming out will solve the blackout screen problem. If map grid shows but no map appears than check the google maps api key.
Update # 3
For Android Google Maps API Ver 2.0 developers follow the following link.

 

1.Download the recovery image form the link below. Use this image in case of  recovering from a disaster. Recovery Image: signed-dream_devphone_userdebug-ota-14721.zip from http://developer.htc.com/adp.html

2. Copy signed-dream_devphone_userdebug-ota-14721.zip to /source/ directory.

3. Go to ‘vendor/htc/dream’  and run ‘./extract-files.sh’, or  ./unzip-files.sh

4. Then, Then apply the following commands

5. source build/envsetup.sh

6. $ lunch aosp_dream_us-eng

7. Compile the modified Android Source Code for the device

8. $ make -j

9. Now the generated files are

10. boot.img,

11. recovery.img,

12. system.img,

13. userdata.img

14.  These files will be located at

15. out/target/product/dream-open/

16.  Put device into FASTBOOT mode

17. reboot

18. power_on the device with BACK key pressed,

19.  It should show the driods on skateboard with fastboot text displayed.

20.  Make sure the cable with the device is connected.

21.  Now apply the following commands

22. sudo su

23. set path to fastboot

24. export PATH=/mydroid/out/host/linux-x86/bin/:$PATH

25.  Stop and start the server

26. adb kill-server

27. adb start-server

28.  Check the fastboot devices

29. #fastboot devices

30.  The above command will show you the fastboot devices.

31. HT94JLZ00002    fastboot

32.  Now apply the following command.

33. #fastboot -p dream-open -w flashall

34.  flashall will apply all the above listed img files one by one. but we can also do that manually by specifying the image file name. After this the flashing will start and our device will be loaded with our own modified source code.

Blog Stats

  • 330,141 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: