Showing posts with label MapView. Show all posts
Showing posts with label MapView. Show all posts

Android Maps Using Google Maps API V2

Since end of last year, Google launch Google Map API V2, so for Android programmer there's a new way to code about Map. In Google Map API V1 we just need a MapActivity, so on the V2 there's a different way to call the Map API.

Beofre starting your project, you must install Google Play Service from your Android SDK, and then import the Google Play Service Library to your project directory, If you don't do this step you can't import all com.google.android.xxx.

Here's same sample code to using Map on your Android Project.


 package com.ademahendramap;
  
 import java.util.List;  
 import com.google.android.gms.maps.CameraUpdateFactory;  
 import com.google.android.gms.maps.GoogleMap;  
 import com.google.android.gms.maps.SupportMapFragment;  
 import com.google.android.gms.maps.model.BitmapDescriptorFactory;  
 import com.google.android.gms.maps.model.LatLng;  
 import com.google.android.gms.maps.model.Marker;  
 import com.google.android.gms.maps.model.MarkerOptions;  
 import com.google.android.gms.maps.model.PolylineOptions;  
 import android.content.Context;  
 import android.content.Intent;  
 import android.graphics.Color;  
 import android.location.Criteria;  
 import android.location.Location;  
 import android.location.LocationListener;  
 import android.location.LocationManager;  
 import android.os.Bundle;  
 import android.provider.Settings;  
 import android.support.v4.app.FragmentActivity;  
 import android.util.Log;  
 import android.widget.Toast;  

 public class MapDirection extends FragmentActivity implements LocationListener {  
   private GoogleMap map;  
   private static final LatLng Malang = new LatLng(-7.955888,112.63481);  
   private LocationManager locationManager;  
   private String provider;  

   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.map_direction);  
      
     map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();  
     LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);  
     boolean enabledGPS = service  
         .isProviderEnabled(LocationManager.GPS_PROVIDER);  
     boolean enabledWiFi = service  
         .isProviderEnabled(LocationManager.NETWORK_PROVIDER);  
     // Check if enabled and if not send user to the GSP settings  
     // Better solution would be to display a dialog and suggesting to   
     // go to the settings  
     if (!enabledGPS) {  
       Toast.makeText(this, "GPS signal not found", Toast.LENGTH_LONG).show();  
       Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);  
       startActivity(intent);  
     }  
     locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);  
     // Define the criteria how to select the locatioin provider -> use  
     // default  
     Criteria criteria = new Criteria();  
     provider = locationManager.getBestProvider(criteria, false);  
     Location location = locationManager.getLastKnownLocation(provider);  
     // Initialize the location fields  
     if (location != null) {  
       Toast.makeText(this, "Current Provider " + provider,  
           Toast.LENGTH_SHORT).show();  
       onLocationChanged(location);  
     } else {  
       //do something  
     }  
   }  
 
   @Override  
   protected void onResume() {  
     super.onResume();  
     locationManager.requestLocationUpdates(provider, 400, 1, this);  
   }  

   @Override  
   protected void onPause() {  
     super.onPause();  
// Remove update of location listener
     locationManager.removeUpdates(this);  
   }  
   @Override  
   public void onLocationChanged(Location location) {  
     double lat = location.getLatitude();  
     double lng = location.getLongitude();  
  
     LatLng coordinate = new LatLng(lat, lng);  
      
     Marker startposition = map.addMarker(new MarkerOptions()  
     .position(coordinate)  
     .title("Start")  
     .snippet("Current Location")  
     .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));  
     
     //centering the map to your marker startposition
     map.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 12));  
   }  

   @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  
   }  
 }  

and here's the xml


 <fragment xmlns:android="http://schemas.android.com/apk/res/android"  
 android:id="@+id/map"  
 android:layout_width="match_parent"  
 android:layout_height="match_parent"  
 class="com.google.android.gms.maps.SupportMapFragment"/>  

Okay, and don't forget to add some sting to your AndroidManifest.xml


             <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />  
           <uses-permission android:name="android.permission.INTERNET" />  
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />  
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />  
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />  
        <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />  
       <uses-feature  
            android:glEsVersion="0x00020000"  
            android:required="true"/>  
   <application  
     android:allowBackup="true"  
     android:icon="@drawable/ic_launcher"  
     android:label="@string/app_name"  
     android:theme="@style/AppTheme" >  
      <meta-data  
          android:name="com.google.android.maps.v2.API_KEY"  
          android:value="YOUR_API_KEY" />  


Using MapView on Android Application

In this tutorial, I'll try to explain how to use  google map on android application using Google Map API's V1.
First you must get an API Key at http://code.google.com/android/maps-api-signup.html before you debugging your application. You must enter your md5 debug.key, you can search on Google how to get md5 API Key.

first you must add some code to your application manifest. That's code will give your application permission to access google maps.

 //permission to get access for internet and location  
 <uses-permission android:name="android.permission.INTERNET"/>  
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />  
 <application>  
 . . . . . . . .  
 <uses-library android:name="com.google.android.maps" />  
 . . . . . . . .   
 </application>  

After you've been add that's code to your application manifest, now you can add to your application layout. Like the code bellow:
           <com.google.android.maps.MapView   
          android:id="@+id/mapView"  
          android:layout_width="290dp"  
          android:layout_height="180dp"           
          android:enabled="true"  
          android:clickable="true"  
          android:layout_gravity="center"  
          android:apiKey="YOUR API KEY PUT HERE" />  

Let's cook the code on your java activity. I'm using GPS to get the location using MyLocation class that's I've been write before. Check my another blog post on Using GPS Satellite.
Declare some variable that's its will be used on mapview.


 public class TodoAddActivity extends MapActivity {  
      MapView mapView;   
      MapController mc;  
   GeoPoint p;  

Code for set MapView. In this code I assume that's you've a Latitude and Longitude value.
      public LocationResult locationResult = new LocationResult(){  
     @Override  
     public void gotLocation(final Location location){  
       //Got the location!  
          Glat = location.getLatitude();  
          Glon = location.getLongitude();  
          mGps.setText(location.getLongitude() + " : " + location.getLatitude());    
          mGps.setEnabled(false);  
          mapView.setVisibility(View.VISIBLE);  
             retrieveLocationButton.setEnabled(true);  
             addnewBtn.setEnabled(true);  
             gpsStatus = true;  
       mapView.invalidate();  
       mc = mapView.getController();  
       p = new GeoPoint(  
         (int) (Glat * 1E6),   
         (int) (Glon * 1E6));  
       mc.animateTo(p);  
       mc.setZoom(17);   
       MapOverlay mapOverlay = new MapOverlay();  
       List<Overlay> listOfOverlays = mapView.getOverlays();  
       listOfOverlays.clear();  
       listOfOverlays.add(mapOverlay);  
       mapView.invalidate();   
       };  
     };  
   class MapOverlay extends com.google.android.maps.Overlay  
   {  
     @Override  
     public boolean draw(Canvas canvas, MapView mapView,   
     boolean shadow, long when)   
     {  
       super.draw(canvas, mapView, shadow);            
       //---translate the GeoPoint to screen pixels---  
       Point screenPts = new Point();  
       mapView.getProjection().toPixels(p, screenPts);  
       //---add the marker---  
       Bitmap bmp = BitmapFactory.decodeResource(  
         getResources(), R.drawable.marker);        
       canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);       
       return true;  
     }  
   }   

There is a Class call MapOverlay. it's use to add marker on your map view. if U don't want an Marker on your map, forget that's class :D. just use that's code, you also can customize your zoom level on mc.setZoom([your value])
     mapView.invalidate();   
     mc = mapView.getController();   
     p = new GeoPoint(   
      (int) (Glat * 1E6),    
      (int) (Glon * 1E6));   
     mc.animateTo(p);   
     mc.setZoom(17);  
Okay. See you in another Android Tutorial.