Google maps is very popular in these days. So most of mobile
apps use Google maps to server their customers. In this tutorial I’m going to
demonstrate how to use Google maps for your android app using Google service
1)
Step is to add Google play serves to
your android adt bundle.
Open Eclipse ⇒ Windows ⇒ Android SDK Manager
Go
to Android SDK Manager and click and check you have Google play serves with
your adt bundle. If not you have to download it.
2)
Like that way you have to check your
adt bundle contain
To check you have to select Obsolete tick on your
android sdk manager window . If not you have to install that also
If you
done now your ready to get privet key from Google services to your android
application.
3)
Then go to the place where java
install in your computer.
Program
Files (x86)\Java\jre7\bin
Then “shift+right click” and open command
prompt
Then type like this
6) Then goto
APIs & auth -> Credentials -> public api access
->create new key -> android key
After you completing typing click the create
button
Then google provide a api key
Copy the API Key. Late you need that.
8) then Create a work place for the project
In
Eclipse goto File ⇒ Import ⇒ Android ⇒ Existing Android Code
Into Workspace
9. Click
on Browse and select Google Play Services project from your android sdk folder.
You can locate play services library project from
android-sdk-windows\extras\google\google_play_services\libproject\google-play-services_lib
android-sdk-windows\extras\google\google_play_services\libproject\google-play-services_lib
10.
Importantly while importing check Copy projects into workspace option as shown in the below
image.
11. In
Eclipse create a new project by going to File ⇒ New ⇒ Android Application
Project and
fill required details. I kept my project name as Google Maps V2 and package name
12. Now
we need to use Google Play Services project as a library to use project . So right
click on project
and select properties. In the
properties window on left side select Android. On the right
you can see Add button under library section. Click it
and select google play services project which we imported previously.
13)
14)
15)at last your workplace is display like this.
16) Then
you need to give permission in manifest file
<! -- Goolge API Key
-- >
<meta-data
<--add your api here as
android: value -- >
<meta-data
<! -- Required OpenGL
ES 2.0. for Maps V2 -- >
<uses -feature
<uses -permission android: name="android. permission. ACCESS_COARSE_LOCATION"
/>
<uses -permission android: name="android. permission. ACCESS_FINE_LOCATION"
/>
<uses -permission android: name="android. permission. INTERNET"
/>
<uses -permission android: name="android. permission. READ_EXTERNAL_STORAGE"
/>
<uses -permission android: name="android. permission. READ_INTERNAL_STORAGE"
/>
<uses -permission android: name="android. permission. ACCESS_NETWORK_STATE"
/>
<uses -permission
android:name
="com.google.android.providers.gsf.permission.READ
_GSERVICES"
/>
17)Setup map
New google maps are implemented using MapFragments which
is a sub class of Fragmentsclass. Open your main activity layout file activity_main.xml file
and add following code . I usedRelativeLayout as a
parent element. You can remove it and use MapFragment directly.
XML
activity_main.xml
|
< version="1.0" encoding="utf-8"?> > < </ |
JAVA CODE
MainActivity.java
|
//
Google Map
@Override
//
Loading map
}
}
}
/**
*
function to
*
*/
R
//
Toast
"Sorry!
}
}
}
@Override
}
}
|
MAP Properties
Showing Current Location
You can show user’s current location on the
map by calling setMyLocationEnabled ( ). Pass true / false to enable or disable this feature
Zooming Buttons
You can call setZoomControlsEnabled ( ) function to get rid of those zooming
controls on the map. By disabling these buttons map zooming functionality still
work by pinching gesture.
Zooming Functionality
You can disable zooming gesture functionality
by calling setZoomGesturesEnabled ( )
Compass Functionality
My Location Button
My location button will be used to move map to
your current location. This button can be shown / hidden by calling setMyLocationButtonEnabled ( ) function
Map Rotate Gesture
My rotate gesture can be enabled or disabled
by calling setRotateGesturesEnabled ( ) method
Although google maps provides lot of other
features, I covered only basic topics in this tutorial. Remaining topics seems
to be pretty much lengthy, so I’ll post them as separate articles.
Changing Map Type
Google provides 4 kinds of map types Normal, Hybrid, Satellite and Terrain.
You can toggle to any kind of map using googleMap . setMapType ( ) method.
Custom Marker Icon
Apart from maps native marker icons, you can
use own image to show as a marker. You can load the icon from any kind of
supported sources.
//
//
// Changing marker
icon
//
|
Moving Camera to a Location with animation
You may want to move camera to a particular
position. Google maps provides set of functions to achieve this.
Following are enhancements and features that google maps
Changing Marker Color
By default map marker color will be RED.
Google maps provides some set of predefined colored icons for the marker.
// ROSE color icon
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// GREEN color icon
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
|
Placing a Marker
You can place a marker on the map by using
following code .
//
//
//
|
Create
Application to get current location & draw the shortest path for the
provided location from the current location
For this first we have
to create two java class call
GPSTracker and GMapV2Direction
GMapV2Direction
java class
String
url = "http://maps.googleapis.com/maps/api/directions/xml?"
+
"origin=" + start. latitude + "," + start. longitude
+
"&destination=" + end. latitude + "," + end. longitude
+
"&sensor=false&units=metric&mode=driving";
Log. d( "GoogleMapsDirection", url);
HttpClient httpClient = new
DefaultHttpClient( );
HttpContext localContext = new
BasicHttpContext( );
//execute in request in http cilent
System. out. println ( "a"+httpPost);
System. out. println ( "b"+localContext);
//sent or received http msg
InputStream in =
response. getEntity ( ). getContent ( );
System. out. println ( "c"+in);
//enables application to obtain paser
that produse DOM object tree from XML
DocumentBuilder builder =
DocumentBuilderFactory. newInstance ( ). newDocumentBuilder ( );
System. out. println ( "d"+builder);
Document doc = builder. parse( in);
System. out. println ( "e"+doc);
} catch (Exception e) {
}
}
Node node1 = nl1. item( nl1.getLength( ) -
1);
Node node2 = nl2. item( getNodeIndex ( nl2,
"text"));
Log. i ( "DurationText", node2.getTextContent( ));
}
Node node1 = nl1. item( nl1.getLength( ) -
1);
Node node2 = nl2. item( getNodeIndex ( nl2,
"value"));
Log. i ( "DurationValue",
node2.getTextContent( ));
}
Node node1 = nl1. item( nl1.getLength( ) -
1);
Node node2 = nl2. item( getNodeIndex ( nl2,
"text"));
Log. i ( "DistanceText ",
node2.getTextContent( ));
}
Node node1 = nl1. item( nl1.getLength( ) -
1);
Node node2 = nl2. item( getNodeIndex ( nl2,
"value"));
Log. i ( "DistanceValue ",
node2.getTextContent( ));
}
Node node1 = nl1. item( 0);
Log. i ( "StartAddress ",
node1.getTextContent( ));
}
Node node1 = nl1. item( 0);
Log. i ( "StartAddress ",
node1.getTextContent( ));
}
Node node1 = nl1. item( 0);
Log. i ( "CopyRights ",
node1.getTextContent( ));
}
//decode the
received String in http mssage to geopints
//Google
provides the routing results as an encoded polylines format
NodeList
nl1, nl2, nl3;
ArrayList<LatLng> listGeopoints =
new
ArrayList<LatLng>();
nl1 = doc. getElementsByTagName ( "step");
Node node1 = nl1. item( i );
nl2 = node1.getChildNodes( );
Node locationNode =
nl2. item( getNodeIndex ( nl2, "start_location"));
nl3 =
locationNode . getChildNodes ( );
Node latNode = nl3. item( getNodeIndex ( nl3,
"lat "));
Node lngNode =
nl3. item( getNodeIndex ( nl3, "lng "));
nl3 =
locationNode . getChildNodes ( );
ArrayList<LatLng> arr =
decodePoly(latNode.getTextContent());
for(int j = 0 ; j <
arr.size() ; j++) {
}
nl3 =
locationNode . getChildNodes ( );
}
}
}
}
}
ArrayList<LatLng>
poly = new ArrayList<LatLng>();
}
while (b >= 0x20);
}
while (b >= 0x20);
}
}
}
// flag for
GPS status
// flag for
network status
// flag for
GPS status
Location
location; // location
// The minimum
distance to change Updates in meters
// The minimum
time between updates in milliseconds
// Declaring a
Location Manager
}
// getting GPS
status( name of loaction provider'gps '(constant))
// getting
network status
// no network
provider is enabled
}
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS
Enabled get lat/long using GPS Services
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log. d( "GPS
Enabled", "GPS Enabled");
longitude = location.getLongitude();
}
}
}
}
}
}
catch (Exception e) {
}
}
//what to do
when no gps
}
}
}
// return
latitude
}
}
// return
longitude
}
//find gps
N wifi anable
}
//show alerts
// Setting Dialog Title
// Setting Dialog Message
// On pressing Settings button
Intent
intent = new Intent( Settings. ACTION_LOCATION_SOURCE_SETTINGS);
//acsess
to the settings option
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new
DialogInterface.OnClickListener() {
public void
onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
}
@Override
}
@Override
}
@Override
}
@Override
}
@Override
}
}
Then we want to create the UI with one
fragment for load the map and two buttons to get the location and draw the path
<? xml version="1.0"
encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
<fragment
<Button
android:id="@+id/button2"
android:layout_width="162dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:text="Draw Location" />
<Button
android:layout_alignParentBottom="true"
<EditText
</RelativeLayout >
Then the java file
EditText
destination;
// GPSTracker
class
GMapV2Direction md ;
Button getloc , drawloc ;
String
lat, lon, temp;
String
locName=destination. getText ( ). toString();
// TODO
Auto-generated method stub
String
addressUrl = "http://maps.googleapis.com/maps/api/geocode/json?address="
+ locName
+ "&sensor=true";
HttpClient httpClient = new
DefaultHttpClient( ); // Client
// HttpPost postRequest = new
HttpPost( );
// postRequest . setURI ( new URI( url));
StringBuffer sb = new StringBuffer( "");
String line = "";
String NL = System. getProperty ( "line. separator");
}
String page = sb . toString();
//mylon . setText ( page);
JSONObject jsonObject = new
JSONObject( page);
JSONArray jsonArray =
(JSONArray) jsonObject.get("results");
//mylon . setText ( locName );
latitude1 = (Double)
location. get ( "lat");
longitude1 = (Double)
location. get ( "lng ");
}
}
}
}
} catch (Exception e) {
} finally {
} catch (IOException e)
{
}
}
}
}
@Override
// TODO
Auto-generated method stub
//interact
with gui only here#######################################
Log. e( locName , latitude1+""+longitude1);
Log. e( "to",""+toPosition);
}
@Override
// TODO
Auto-generated method stub
locName=destination. getText ( ). toString();
Log. e( "Name", locName );
}
}
String
url = "http://maps.googleapis.com/maps/api/directions/xml?"
+
"origin=" + start. latitude + "," + start. longitude
+
"&destination=" + end. latitude + "," + end. longitude
+
"&sensor=false&units=metric&mode=driving";
Log. d( "GoogleMapsDirection", url);
HttpClient httpClient = new
DefaultHttpClient( );
HttpContext localContext = new
BasicHttpContext( );
//execute in request in http cilent
Log. d( "httpPost ", url);
Log. d( "localContext ",""+ localContext );
Log. d( "response",""+ response);
//sent or received http msg
InputStream in =
response. getEntity ( ). getContent ( );
Log. d( "in",""+ in);
//enables application to obtain paser
that produse DOM object tree from XML
DocumentBuilder builder =
DocumentBuilderFactory. newInstance ( ). newDocumentBuilder ( );
Log. d( "builder",""+ builder);
Document doc = builder. parse( in);
Log. d( "doc",""+ doc);
} catch (Exception e) {
}
}
{
Log. e( "from",""+fromPosition);
Log. e( "to",""+toPosition);
//Document doc
= md . getDocument ( fromPosition , toPosition , GMapV2Direction.MODE_DRIVING);
Document
doc = getDocument ( fromPosition , toPosition , GMapV2Direction.MODE_DRIVING);
Log. e( "md ",""+md);
Log. e( "mMap ",""+mMap);
Log. e( "doc",""+doc);
ArrayList<LatLng>
directionPoint = md.getDirection(doc);
//directionPoint
the array returned by the decodePoly method are stored
}
}
@TargetApi( Build. VERSION_CODES. HONEYCOMB)
getloc=( Button) findViewById( R. id. button1);
drawloc=( Button) findViewById( R. id. button2);
Log. e( "i 'm look
ing @2","ggggggggg");
//load the default map to web view
R. id. map)). getMap ( );
@Override
// TODO
Auto-generated method stub
// create
class object
gps = new
GPSTracker(GetLocation.this);
// check if GPS
enabled
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
longt = longitude;
lati = latitude;
Toast.makeText(getApplicationContext(),
"Your
Location is - \nLat: " + latitude + "\nLong: " + longitude,
Toast.LENGTH_LONG).show();
fromPosition=new
LatLng(latitude,longitude);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(fromPosition, 16));
mMap.setMyLocationEnabled(true);
}else{
gps.showSettingsAlert();
}
}
});
drawloc.setOnClickListener(new
View.OnClickListener() {
@Override
// TODO
Auto-generated method stub
}
});
}
}