Showing posts with label map. Show all posts
Showing posts with label map. Show all posts

Tuesday, May 8, 2012

How to Use Google Maps in Android Application


How to Use Google Maps in Android Application



This tutorial demonstrates how to display Google Maps in an Android application.

Download Google APIs

To use Google Maps in your application, you need to download specific Google APIs. If you already downloaded the Google APIs then skip this step otherwise follow these instructions to download the updated Google APIs of your desired version.
Start SDK Manager from the Android SDK folder on your computer. Click on the Available Packages.
Click and expand third party Add-ons folder. You will see Google Inc folder. Expand this folder and select the desired version of APIs you want to install.
Click on the "Install Selected" button at the bottom, to install the APIs.
Android SDK Manager

Create Virtual Device

Next you need to create a specific virtual device that uses the Google API of your desired version. To create the virtual device, click on the "Virtual Devices" option in the left menu.
Click on the New button to create a new virtual device. Enter appropriate name for your virtual device. Select the desired version of Google API from "Target" drop down. Input some value in Size text box and click the "Create AVD" button to create the virtual device.
Upon successful creation select the newly created device and click the "Start" button to start the virtual device.

Get Google Map API Key

The next step is to get the Google Map Api Key. To get the key visit Google code project athttp://code.google.com/android/add-ons/google-apis/maps-api-signup.html . At the bottom of the page you will find a text box to input MD5 fingerprint.

You can get your certificate's MD5 fingerprint from your local machine. To create MD5 fingerprint you need to run "Keytool"  utility that comes with the JRE.
As you are working in development environment, first you need to find the location of debug certificate. In Eclipse, click Window -> Preferences -> Android -> Build.  You can see default debug keystore. Copy it to clipboard.
Now open the command window and type following command at command prompt.
keytool -list - alias androiddebugkey -keystore "Path to keystore debugkey" -storepass android -keypass android
Replace the string "Path to keystore debugkey" in above line with your computer's path of keystore debugkey. Now press enter and keytool utility will create the fingerprint and display it on the screen - copy this finger print.
Go back to the Google code project web page (you opened in the above steps) paste or type your MD5 finger print in the text area  for "My certificate's MD5 fingerprint:". Press "Generate API key" button.

It will generate the API key and bring you to the next page. You need to sign in with your Google account.
 
In the above image you can see the generated key and the sample code for your android application's layout xml file. Copy the sample code for your generated key so that you can use it in your application.

Android Application

Now open the Eclipse and create a new Android project. This time for "Buid Target", select the "Google APIs" of your desired version. Fill rest of the fields and create the project.
Open the main.xml layout file of your project and make changes according to the code given below. Remember to replace API Key with the key you generated using MD5 fingerprint from your computer.  Assign a unique id to your map view, as you will access it from the application code. If you want your map to be interactive and clickable then set its clickable property to true.
The final xml layout file should be looking similar to the following code.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<com.google.android.maps.MapView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/my_map"
android:clickable="true"
android:apiKey="0WkC5ANoCR9utisPeoO17OlP7TxcKAFwQovvgiQ"
/>
</LinearLayout>
Now open AndroidManifest.xml file. You need to add internet permissions to your application, as your application will use internet to access the map. Add following line of code to your manifest file.
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
You also need to include the Google API. Add following line under the application tag.
<uses-library android:name= "com.google.android.maps" />
Here is the sample code of updated manifest file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.alam.android.mapapp"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="10" />
   
   <uses-permission android:name="android.permission.INTERNET"></uses-permission>
   
    <application android:icon="@drawable/icon" android:label="@string/app_name">
   
  <uses-library android:name= "com.google.android.maps" />
   
        <activity android:name=".MainActivity"
                  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>

Now open the MainActivity.java and extend it from the MapActivity, instead of Activity class.
public class MainActivity extends MapActivity
If you get any errors, import the MapView and add the un-implemented methods. At this point your application is ready to run and display a map in the emulator.
If you want to add a built-in zoom control to your map then go ahead and follow these instructions.
In the onCreate method, get a reference to MapView that is defined in the xml layout file.
MapView mView = (MapView) findViewById(R.id.my_map);
Set the built-in zoom control by calling
mView.setBuiltInZoomControls(true);
Final code for MainActivity.java
public class MainActivity extends MapActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
      
        // Get a reference to MapView
        MapView mView = (MapView) findViewById(R.id.my_map);
        // Set the built-in zoom control
        mView.setBuiltInZoomControls(true);
    }

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

}

How to display route between two points (geopoints) on Google Maps in Android


How to display route between two points (geopoints) on Google Maps in Android


Recently a have some task in my Android project.
I needed to show route (directions) between two points (geopoins)on google maps in Android.
I thought it can be simple task. But It was a lot of interesting things :).
I’ve discovered a lot of topics of this problem.
I find one usefull. This is IT
But, it didn’t works for me.
Here I want to show my changes of this project.

Android Google Maps. How to show route between two geopoints on map.



RoadProvider.java
------------------
import java.io.InputStream; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; public class RoadProvider { private static Document xmlDocument; public static Road getRoute(InputStream is) { Road mRoad = new Road(); String expression = "string(//Placemark/GeometryCollection/LineString/coordinates)"; String expression2 = "string(//Placemark[contains(name, 'Route')]/description)"; try { xmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is); XPathFactory xPathFactory = XPathFactory.newInstance(); XPath xPath = xPathFactory.newXPath(); XPathExpression xPathExpression = xPath.compile(expression); String result = xPathExpression.evaluate(xmlDocument); String[] arr1 = result.split(" "); for (String str : arr1) { String[] coords = str.split(","); if (coords.length == 3) { double[] xy = new double[] {}; double x = Double.parseDouble(coords[0]); double y = Double.parseDouble(coords[1]); xy = addDouble(xy, x); xy = addDouble(xy, y); mRoad.mRoute = addDouble(mRoad.mRoute, xy); System.out.println("PARSING ..... "); } } xPathExpression = xPath.compile(expression2); String description = xPathExpression.evaluate(xmlDocument); mRoad.mDescription = cleanup(description); System.out.println("DESCRIPTION = " + mRoad.mDescription); } catch (Exception ex) { ex.printStackTrace(); } return mRoad; } static double[][] addDouble(double[][] array, double[] element) { int arrayLength = array.length; double[][] result = new double[arrayLength + 1][]; for (int i = 0; i < arrayLength; i++) { int elementLength = array[i].length; result[i] = new double[elementLength]; for (int j = 0; j < elementLength; j++) result[i][j] = array[i][j]; } int newElementLength = element.length; result[arrayLength] = new double[newElementLength]; for (int j = 0; j < newElementLength; j++) result[arrayLength][j] = element[j]; return result; } static double[] addDouble(double[] array, double element) { int arrayLength = array.length; double[] result = new double[arrayLength + 1]; for (int i = 0; i < arrayLength; i++) result[i] = array[i]; result[arrayLength] = element; return result; } public static String getUrl(double fromLat, double fromLon, double toLat, double toLon) { StringBuffer urlString = new StringBuffer(); urlString.append("http://maps.google.com/maps?f=d&amp;hl=en"); urlString.append("&amp;saddr="); urlString.append(Double.toString(fromLat)); urlString.append(","); urlString.append(Double.toString(fromLon)); urlString.append("&amp;daddr="); urlString.append(Double.toString(toLat)); urlString.append(","); urlString.append(Double.toString(toLon)); urlString.append("&amp;ie=UTF8&amp;0&amp;om=0&amp;output=kml"); return urlString.toString(); } private static String cleanup(String value) { String remove = "<br/>"; int index = value.indexOf(remove); if (index != -1) value = value.substring(0, index); remove = "&amp;#160;"; index = value.indexOf(remove); int len = remove.length(); while (index != -1) { value = value.substring(0, index).concat(value.substring(index + len, value.length())); index = value.indexOf(remove); } return value; } }





Friday, May 4, 2012

My location and Google Map

My location and Google Map


This is very good example for getting user location with the map  
and display in the map with circle like in the goggle map with twinkling bubble 








package app.test;

import android.os.Bundle;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;

public class MyLocationDemoActivity extends MapActivity {
    
    MapView mapView = null;
    MapController mapController = null;
    MyLocationOverlay whereAmI = null;
    
    @Override
    protected boolean isLocationDisplayed() {
        return whereAmI.isMyLocationEnabled();
    }
    
    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }

    /** 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.geoMap);
        mapView.setBuiltInZoomControls(true);

        mapController = mapView.getController();
        mapController.setZoom(15);

        whereAmI = new MyLocationOverlay(this, mapView);
        mapView.getOverlays().add(whereAmI);
        mapView.postInvalidate();
    }

    @Override
    public void onResume()
    {
        super.onResume();
        whereAmI.enableMyLocation();
        whereAmI.runOnFirstFix(new Runnable() {
            public void run() {
                mapController.setCenter(whereAmI.getMyLocation());
            }
        });
    }

    @Override
    public void onPause()
    {
        super.onPause();
        whereAmI.disableMyLocation();
    }
}
<?xml version="1.0" encoding="utf-8"?>
<!-- This file is /res/layout/main.xml -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

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

</RelativeLayout>

Thursday, May 3, 2012

Updating User Location

Updating User Location




Android supports location-based services, as you'd expect from any modern mobile OS. In Android, LocationManager is responsible for handling this.

To get the location manager, we ask the context to getSystemService() for location services. Next we ask the location manager for list of all available providers.


You may not care about all available location providers but just want to get the best one available. To do this, we specify our criteria for "best". For example, do we require altitude and bearing, allow cost, etc.

We can now ask the location manager for the last known location, for the specific provider. This is helpful to quickly place you close to last location, while waiting for updates to come in.

It is important to register with the location manager to receive the location updates. To do so, we recommend the onResume(). Also, you should unregister from location notifications in your onPause(). Tracking your location can be expensive on the battery and CPU of the device, so this is good practice to stop doing the work while we are paused and normally don't care about the updates. This is important.

The LocationListener which we are implementing will allow us to get certain callbacks. Those callbacks include location, provider and status changes.

LocationDemo.java
Code:
package com.marakana;

import java.util.List;

import android.app.Activity;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.widget.TextView;

public class LocationDemo extends Activity implements LocationListener {
 private static final String TAG = "LocationDemo";
 private static final String[] S = { "Out of Service",
   "Temporarily Unavailable", "Available" };

 private TextView output;
 private LocationManager locationManager;
 private String bestProvider;

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

  // Get the output UI
  output = (TextView) findViewById(R.id.output);

  // Get the location manager
  locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

  // List all providers:
  List<String> providers = locationManager.getAllProviders();
  for (String provider : providers) {
   printProvider(provider);
  }

  Criteria criteria = new Criteria();
  bestProvider = locationManager.getBestProvider(criteria, false);
  output.append("\n\nBEST Provider:\n");
  printProvider(bestProvider);

  output.append("\n\nLocations (starting with last known):");
  Location location = locationManager.getLastKnownLocation(bestProvider);
  printLocation(location);
 }

 /** Register for the updates when Activity is in foreground */
 @Override
 protected void onResume() {
  super.onResume();
  locationManager.requestLocationUpdates(bestProvider, 20000, 1, this);
 }

 /** Stop the updates when Activity is paused */
 @Override
 protected void onPause() {
  super.onPause();
  locationManager.removeUpdates(this);
 }

 public void onLocationChanged(Location location) {
  printLocation(location);
 }

 public void onProviderDisabled(String provider) {
  // let okProvider be bestProvider
  // re-register for updates
  output.append("\n\nProvider Disabled: " + provider);
 }

 public void onProviderEnabled(String provider) {
  // is provider better than bestProvider?
  // is yes, bestProvider = provider
  output.append("\n\nProvider Enabled: " + provider);
 }

 public void onStatusChanged(String provider, int status, Bundle extras) {
  output.append("\n\nProvider Status Changed: " + provider + ", Status="
    + S[status] + ", Extras=" + extras);
 }

 private void printProvider(String provider) {
  LocationProvider info = locationManager.getProvider(provider);
  output.append(info.toString() + "\n\n");
 }

 private void printLocation(Location location) {
  if (location == null)
   output.append("\nLocation[unknown]\n\n");
  else
   output.append("\n\n" + location.toString());
 }

}


The layout file for this application is trivial. It uses a single TextView for the output. Yes, we could use maps to show the location, but that's subject of another demo.

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

  <ScrollView android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <TextView android:id="@+id/output" android:layout_width="fill_parent"
      android:layout_height="wrap_content" />
  </ScrollView>
</LinearLayout>



And finally, remember to add the appropriate permissions to your AndroidManifest.xml file

AndroidManifest.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.marakana" android:versionCode="1" android:versionName="1.0.0">
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
  <application android:icon="@drawable/icon" android:label="@string/app_name"
    android:theme="@android:style/Theme.Light">
    <activity android:name=".LocationDemo" 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> 



The output should look similar to this:

Friday, April 20, 2012

Location Manager Examples


Location Manager Examples
Here theres is a small program regarding location manager and location class 


package com.vinnysoft.ami; 


import java.util.List; 
import java.util.Locale; 


import android.app.Activity; 
import android.content.Context; 
import android.location.Address; 
import android.location.Criteria; 
import android.location.Geocoder; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.widget.TextView; 


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


LocationManager locationManager; 
String context = Context.LOCATION_SERVICE; 
locationManager = (LocationManager)getSystemService(context); 


Criteria crta = new Criteria(); 
crta.setAccuracy(Criteria.ACCURACY_FINE); 
crta.setAltitudeRequired(false); 
crta.setBearingRequired(false); 
crta.setCostAllowed(true); 
crta.setPowerRequirement(Criteria.POWER_LOW); 
String provider = locationManager.getBestProvider(crta, true); 


// String provider = LocationManager.GPS_PROVIDER; 
Location location = locationManager.getLastKnownLocation(provider); 
updateWithNewLocation(location); 


locationManager.requestLocationUpdates(provider, 1000, 0, locationListener); 



private final LocationListener locationListener = new LocationListener() 



@Override 
public void onLocationChanged(Location location) { 
updateWithNewLocation(location); 



@Override 
public void onProviderDisabled(String provider) { 
updateWithNewLocation(null); 



@Override 
public void onProviderEnabled(String provider) { 



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



}; 
private void updateWithNewLocation(Location location) { 
String latLong; 
TextView myLocation; 
myLocation = (TextView) findViewById(R.id.myLocation); 


String addressString = "no address found"; 


if(location!=null) { 
double lat = location.getLatitude(); 
double lon = location.getLongitude(); 
latLong = "Lat:" + lat + "\nLong:" + lon; 


double lattitude = location.getLatitude(); 
double longitude = location.getLongitude(); 


Geocoder gc = new Geocoder(this,Locale.getDefault()); 
try { 
List
addresses= gc.getFromLocation(lattitude, longitude, 1); 
StringBuilder sb = new StringBuilder(); 
if(addresses.size()>0) { 
Address address = addresses.get(0); 
for(int i =0;i sb.append(address.getAddressLine(i)).append("\n"); 
sb.append(address.getLocality()).append("\n"); 
sb.append(address.getPostalCode()).append("\n"); 
sb.append(address.getCountryName()); 

addressString = sb.toString(); 

}catch (Exception e) { 

} else { 
latLong = " NO Location Found "; 

myLocation.setText("your Current Position is :\n" +latLong + "\n " + addressString ); 






add mapview in main.xml file 


give the permission sin android manifest file 

Sunday, April 8, 2012

Get cell location on a GSM phone, getCellLocation()


Get cell location on a GSM phone, getCellLocation()

TelephonyManager.getCellLocation() return the current location of the device.

We need the following permission in this example:
  • android.permission.ACCESS_COARSE_LOCATION
  • android.permission.ACCESS_FINE_LOCATION
  • android.permission.READ_PHONE_STATE


Get cell location on a GSM phone, getCellLocation()

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.AndroidTelephonyManager;
 
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.widget.TextView;
 
public class AndroidTelephonyManager extends Activity {
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      TextView textGsmCellLocation = (TextView)findViewById(R.id.gsmcelllocation);
      TextView textCID = (TextView)findViewById(R.id.cid);
      TextView textLAC = (TextView)findViewById(R.id.lac);
     
      //retrieve a reference to an instance of TelephonyManager
      TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
      GsmCellLocation cellLocation = (GsmCellLocation)telephonyManager.getCellLocation();
     
      int cid = cellLocation.getCid();
      int lac = cellLocation.getLac();
      textGsmCellLocation.setText(cellLocation.toString());
      textCID.setText("gsm cell id: " + String.valueOf(cid));
      textLAC.setText("gsm location area code: " + String.valueOf(lac));
  }
}


?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
<TextView
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="@string/hello"
  />
<TextView
  android:id="@+id/gsmcelllocation"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  />
<TextView
  android:id="@+id/cid"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  />
<TextView
  android:id="@+id/lac"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  />
</LinearLayout>