Tuesday, 12 November 2013

Retain markers on screen rotation in Google Maps Android API V2 using Parcelable LatLng points

Step 1 :- Create New Android Project.



Step 2 :- Add Google-play-services_lib to your project.

Step 3 :- Open AndroidManifest.xml file.

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
   
    <permission
          android:name="com.mapv2.demo.permission.MAPS_RECEIVE"
          android:protectionLevel="signature"/>

    <uses-permission android:name="com.mapv2.demo.permission.MAPS_RECEIVE"/>

    <uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
        <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    <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" >
        <activity
            android:name="com.mapv2.demo.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>
       
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyCmX7SLVHXxU9pSqb2QbAOvdnjAGUulOrk" />
       
    </application>

</manifest>

Step 4 :- Open activity_main.xml.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <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"/>
</RelativeLayout>

Step 5 :- Open MainActivity.java

package com.mapv2.demo;

import java.util.ArrayList;

import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends FragmentActivity {
   
    GoogleMap mGoogleMap;
   
    ArrayList<LatLng> pointList = new ArrayList<LatLng>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        // Getting Google Play availability status
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

        // Showing status
        if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available

            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
            dialog.show();

        }else { // Google Play Services are available           

            // Getting reference to the SupportMapFragment of activity_main.xml
            SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

            // Getting GoogleMap object from the fragment
            mGoogleMap = fm.getMap();

            // Enabling MyLocation Layer of Google Map
            mGoogleMap.setMyLocationEnabled(true);
           
           
            mGoogleMap.setOnMapClickListener(new OnMapClickListener(){
               
                @Override
                public void onMapClick(LatLng point) {
                   
                    // Drawing the currently touched marker on the map
                    drawMarker(point);   
                   
                    // Adding the currently created marker position to the arraylist
                    pointList.add(point);
                                   
                    Toast.makeText(getBaseContext(), "Marker is added to the Map", Toast.LENGTH_SHORT).show();                   
                }
            });             
           
            // Restoring the markers on configuration changes
            if(savedInstanceState!=null){
                if(savedInstanceState.containsKey("points")){
                    pointList = savedInstanceState.getParcelableArrayList("points");
                    if(pointList!=null){
                        for(int i=0;i<pointList.size();i++){
                            drawMarker(pointList.get(i));
                        }
                    }
                }
            }                                          
        }       
    }
   
    // Draw a marker at the "point"
    private void drawMarker(LatLng point){
        // Creating an instance of MarkerOptions
        MarkerOptions markerOptions = new MarkerOptions();                   
           
        // Setting latitude and longitude for the marker
        markerOptions.position(point);
       
        // Setting a title for this marker
        markerOptions.title("Lat:"+point.latitude+","+"Lng:"+point.longitude);
           
        // Adding marker on the Google Map
        mGoogleMap.addMarker(markerOptions);      
    }
   
    // A callback method, which is invoked on configuration is changed
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        // Adding the pointList arraylist to Bundle
        outState.putParcelableArrayList("points", pointList);
       
        // Saving the bundle
        super.onSaveInstanceState(outState);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

Step 6 :- Run Code.



Step 7 :- Download Code :-  https://dl.dropboxusercontent.com/u/109954727/Map/map28.zip

Adding and removing multiple proximity alerts in Google Maps Android API V2

Step 1 :- Create New Android Project.



Step 2 :- Add Google-play-services_lib to your project.

Step 3 :- Open AndroidManifest.xml file.

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
   
    <permission
          android:name="com.mapv2.demo.permission.MAPS_RECEIVE"
          android:protectionLevel="signature"/>
   
    <uses-permission android:name="com.mapv2.demo.permission.MAPS_RECEIVE"/>

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>  
   

    <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" >
        <activity
            android:name="com.mapv2.demo.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>
       
         <activity
            android:name=".ProximityActivity"
            android:label="@string/app_name" >
            <intent-filter >
                <action android:name="in.wptrafficanalyzer.activity.proximity"/>
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

        <activity
            android:name=".NotificationView"
            android:label="@string/app_name" >

            <intent-filter >
                <category android:name="android.intent.category.DEFAULT" />
                </intent-filter>

        </activity>
       
       
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyCmX7SLVHXxU9pSqb2QbAOvdnjAGUulOrk"/>
       
    </application>

</manifest>

Step 4 :- Open activity_main.xml.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <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"/>
</RelativeLayout>


1.)   notification.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
   
    <TextView
        android:id="@+id/tv_notification"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</LinearLayout>



Step 5 :- Open MainActivity.java

package com.mapv2.demo;

import android.app.Dialog;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends FragmentActivity {
   
    GoogleMap googleMap;
    LocationManager locationManager;
    PendingIntent pendingIntent;
    SharedPreferences sharedPreferences;
    int locationCount = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
       
        // Getting Google Play availability status
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

        // Showing status
        if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available

            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
            dialog.show();

        }else { // Google Play Services are available           

            // Getting reference to the SupportMapFragment of activity_main.xml
            SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

            // Getting GoogleMap object from the fragment
            googleMap = fm.getMap();

            // Enabling MyLocation Layer of Google Map
            googleMap.setMyLocationEnabled(true);          
           
           
            // Getting LocationManager object from System Service LOCATION_SERVICE
            locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
           
           
            // Opening the sharedPreferences object
            sharedPreferences = getSharedPreferences("location", 0);
           
            // Getting number of locations already stored
            locationCount = sharedPreferences.getInt("locationCount", 0);           
           
            // Getting stored zoom level if exists else return 0
            String zoom = sharedPreferences.getString("zoom", "0");           
           
            // If locations are already saved
            if(locationCount!=0){

                    String lat = "";
                    String lng = "";

                    // Iterating through all the locations stored
                    for(int i=0;i<locationCount;i++){

                            // Getting the latitude of the i-th location
                            lat = sharedPreferences.getString("lat"+i,"0");

                            // Getting the longitude of the i-th location
                            lng = sharedPreferences.getString("lng"+i,"0");

                            // Drawing marker on the map
                            drawMarker(new LatLng(Double.parseDouble(lat), Double.parseDouble(lng)));
                           
                            // Drawing circle on the map
                            drawCircle(new LatLng(Double.parseDouble(lat), Double.parseDouble(lng)));
                    }

                    // Moving CameraPosition to last clicked position
                    googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(Double.parseDouble(lat), Double.parseDouble(lng))));

                    // Setting the zoom level in the map on last position  is clicked
                    googleMap.animateCamera(CameraUpdateFactory.zoomTo(Float.parseFloat(zoom)));                                                  
            }          
           
           
            googleMap.setOnMapClickListener(new OnMapClickListener() {
               
                @Override
                public void onMapClick(LatLng point) {               
                   
                    // Incrementing location count
                    locationCount++;
                                       
                    // Drawing marker on the map
                    drawMarker(point);
                   
                    // Drawing circle on the map
                    drawCircle(point);                   
                   
                    // This intent will call the activity ProximityActivity
                    Intent proximityIntent = new Intent("in.wptrafficanalyzer.activity.proximity");
                   
                    // Passing latitude to the PendingActivity
                    proximityIntent.putExtra("lat",point.latitude);
                   
                   
                    // Passing longitude to the PendingActivity
                    proximityIntent.putExtra("lng", point.longitude);
                   
                    // Creating a pending intent which will be invoked by LocationManager when the specified region is
                    // entered or exited
                    pendingIntent = PendingIntent.getActivity(getBaseContext(), 0, proximityIntent,Intent.FLAG_ACTIVITY_NEW_TASK);
                   
                   
                    // Setting proximity alert
                    // The pending intent will be invoked when the device enters or exits the region 20 meters
                    // away from the marked point
                    // The -1 indicates that, the monitor will not be expired
                    locationManager.addProximityAlert(point.latitude, point.longitude, 20, -1, pendingIntent);               
                   
                    /** Opening the editor object to write data to sharedPreferences */
                    SharedPreferences.Editor editor = sharedPreferences.edit();

                    // Storing the latitude for the i-th location
                    editor.putString("lat"+ Integer.toString((locationCount-1)), Double.toString(point.latitude));

                    // Storing the longitude for the i-th location
                    editor.putString("lng"+ Integer.toString((locationCount-1)), Double.toString(point.longitude));

                    // Storing the count of locations or marker count
                    editor.putInt("locationCount", locationCount);
                   
                    /** Storing the zoom level to the shared preferences */
                    editor.putString("zoom", Float.toString(googleMap.getCameraPosition().zoom));               

                    /** Saving the values stored in the shared preferences */
                    editor.commit();               
                   
                    Toast.makeText(getBaseContext(), "Proximity Alert is added", Toast.LENGTH_SHORT).show();                   
                   
                }
            });   
           
            googleMap.setOnMapLongClickListener(new OnMapLongClickListener() {               
                @Override
                public void onMapLongClick(LatLng point) {
                    Intent proximityIntent = new Intent("in.wptrafficanalyzer.activity.proximity");
                   
                    pendingIntent = PendingIntent.getActivity(getBaseContext(), 0, proximityIntent,Intent.FLAG_ACTIVITY_NEW_TASK);
                   
                    // Removing the proximity alert                   
                    locationManager.removeProximityAlert(pendingIntent);
                   
                    // Removing the marker and circle from the Google Map
                    googleMap.clear();
                   
                    // Opening the editor object to delete data from sharedPreferences
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                   
                    // Clearing the editor
                    editor.clear();
                   
                    // Committing the changes
                    editor.commit();
                   
                    Toast.makeText(getBaseContext(), "Proximity Alert is removed", Toast.LENGTH_LONG).show();
                }
            });          
        }       
    }
   
   
    private void drawCircle(LatLng point){
       
        // Instantiating CircleOptions to draw a circle around the marker
        CircleOptions circleOptions = new CircleOptions();
       
        // Specifying the center of the circle
        circleOptions.center(point);
       
        // Radius of the circle
        circleOptions.radius(20);
       
        // Border color of the circle
        circleOptions.strokeColor(Color.BLACK);
       
        // Fill color of the circle
        circleOptions.fillColor(0x30ff0000);
       
        // Border width of the circle
        circleOptions.strokeWidth(2);
       
        // Adding the circle to the GoogleMap
        googleMap.addCircle(circleOptions);
       
    }   
   
    private void drawMarker(LatLng point){
        // Creating an instance of MarkerOptions
        MarkerOptions markerOptions = new MarkerOptions();                   
       
        // Setting latitude and longitude for the marker
        markerOptions.position(point);
       
        // Adding InfoWindow title
        markerOptions.title("Location Coordinates");       
       
        // Adding InfoWindow contents
        markerOptions.snippet(Double.toString(point.latitude) + "," + Double.toString(point.longitude));       
       
        // Adding marker on the Google Map
        googleMap.addMarker(markerOptions);
       
    }
   

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}




1.)  NotificationView.java

package com.mapv2.demo;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class NotificationView extends Activity {
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.notification);
       
        TextView tv = (TextView) findViewById(R.id.tv_notification);
        Bundle data = getIntent().getExtras();
        tv.setText(data.getString("content"));       
    }
}



2.)  ProximityActivity.java

package com.mapv2.demo;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;



public class ProximityActivity extends Activity {
   
    String notificationTitle;
    String notificationContent;
    String tickerMessage;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
       
       
        boolean proximity_entering = getIntent().getBooleanExtra(LocationManager.KEY_PROXIMITY_ENTERING, true);
       
        double lat = getIntent().getDoubleExtra("lat", 0);
       
        double lng = getIntent().getDoubleExtra("lng", 0);
       
        String strLocation = Double.toString(lat)+","+Double.toString(lng);
       
        if(proximity_entering){
            Toast.makeText(getBaseContext(),"Entering the region"  ,Toast.LENGTH_LONG).show();
            notificationTitle = "Proximity - Entry";
            notificationContent = "Entered the region:" + strLocation;
            tickerMessage = "Entered the region:" + strLocation;
        }else{
            Toast.makeText(getBaseContext(),"Exiting the region"  ,Toast.LENGTH_LONG).show();
            notificationTitle = "Proximity - Exit";
            notificationContent = "Exited the region:" + strLocation;
            tickerMessage = "Exited the region:" + strLocation;
        }
       
       
       
        Intent notificationIntent = new Intent(getApplicationContext(),NotificationView.class);
       
        /** Adding content to the notificationIntent, which will be displayed on
         * viewing the notification
         */
        notificationIntent.putExtra("content", notificationContent );
       
        /** This is needed to make this intent different from its previous intents */
        notificationIntent.setData(Uri.parse("tel:/"+ (int)System.currentTimeMillis()));
       
        /** Creating different tasks for each notification. See the flag Intent.FLAG_ACTIVITY_NEW_TASK */
        PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
       
        /** Getting the System service NotificationManager */
        NotificationManager nManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
       
        /** Configuring notification builder to create a notification */
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext())
                            .setWhen(System.currentTimeMillis())
                            .setContentText(notificationContent)
                            .setContentTitle(notificationTitle)
                            .setSmallIcon(R.drawable.ic_launcher)
                            .setAutoCancel(true)
                            .setTicker(tickerMessage)
                            .setContentIntent(pendingIntent)
                            .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
       
       
        /** Creating a notification from the notification builder */
        Notification notification = notificationBuilder.build();
       
        /** Sending the notification to system.
         * The first argument ensures that each notification is having a unique id
         * If two notifications share same notification id, then the last notification replaces the first notification
         * */
        nManager.notify((int)System.currentTimeMillis(), notification);
       
        /** Finishes the execution of this activity */
        finish();
       
       
    }
}

Step 6 :- Run Code.




Step 7 :- Download Code :-  https://dl.dropboxusercontent.com/u/109954727/Map/map27.zip

Updating InfoWindow contents with coordinates when dragging marker in Google Maps Android API V2

Step 1 :- Create New Android Project.



Step 2 :- Add Google-play-services_lib to your project.

Step 3 :- Open AndroidManifest.xml file.

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
   
     <permission
          android:name="com.mapv2.demo.permission.MAPS_RECEIVE"
          android:protectionLevel="signature"/>

    <uses-permission android:name="com.mapv2.demo.permission.MAPS_RECEIVE"/>

    <uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
        <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>


    <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" >
        <activity
            android:name="com.mapv2.demo.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>
       
        <meta-data
                android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyCmX7SLVHXxU9pSqb2QbAOvdnjAGUulOrk" />
       
    </application>

</manifest>

Step 4 :- Open activity_main.xml.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <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"/>
</RelativeLayout>

Step 5 :- Open MainActivity.java

package com.mapv2.demo;

import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerDragListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends FragmentActivity {
   
    GoogleMap googleMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Getting Google Play availability status
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());


        if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available

            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
            dialog.show();

        }else { // Google Play Services are available          

            // Getting reference to the SupportMapFragment of activity_main.xml
            SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

            // Getting GoogleMap object from the fragment
            googleMap = fm.getMap();

            // Enabling MyLocation Layer of Google Map
            googleMap.setMyLocationEnabled(true);
           
            googleMap.setOnMapClickListener(new OnMapClickListener() {
               
                @Override
                public void onMapClick(LatLng point) {
                    drawMarker(point);
                   
                }
            });
           
            googleMap.setOnMarkerDragListener(new OnMarkerDragListener() {
               
                @Override
                public void onMarkerDragStart(Marker marker) {
                    // TODO Auto-generated method stub
                   
                }
               
                @Override
                public void onMarkerDragEnd(Marker marker) {
                    // TODO Auto-generated method stub                  
                }
               
                @Override
                public void onMarkerDrag(Marker marker) {
                   
                    // Getting the current position of the marker
                    LatLng pos = marker.getPosition();
                   
                    // Updating the infowindow contents with the new marker coordinates
                    marker.setSnippet(pos.latitude + "," + pos.longitude);              
                   
                    // Updating the infowindow for the user
                    marker.showInfoWindow();
                   
                }
            });           
        }
    }
   
   
    private void drawMarker(LatLng point){
        // Creating an instance of MarkerOptions
        MarkerOptions markerOptions = new MarkerOptions();

        // Setting latitude and longitude for the marker
        markerOptions.position(point);
       
        // Making this marker draggable
        markerOptions.draggable(true);
       
        // Title for this marker
        markerOptions.title("Marker Coordinates");
       
        // Coordinates for this marker as infowindow contents
        markerOptions.snippet(Double.toString(point.latitude)+","+Double.toString(point.longitude));

        // Adding marker on the Google Map
        googleMap.addMarker(markerOptions);       
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

Step 6 :- Run Code.



Step 7 :- Download Code :-  https://dl.dropboxusercontent.com/u/109954727/Map/map26.zip

Remove a single marker from Google Maps Android API V2 on clicking InfoWindow

Step 1 :- Create New Android Project.



Step 2 :- Add Google-play-services_lib to your project.

Step 3 :- Open AndroidManifest.xml file.

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
   
   
    <permission
          android:name="com.mapv2.demo.permission.MAPS_RECEIVE"
          android:protectionLevel="signature"/>

    <uses-permission android:name="com.mapv2.demo.permission.MAPS_RECEIVE"/>

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>


    <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" >
        <activity
            android:name="com.mapv2.demo.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>
       
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyCmX7SLVHXxU9pSqb2QbAOvdnjAGUulOrk" />
       
    </application>

</manifest>

Step 4 :- Open activity_main.xml.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <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"/>
</RelativeLayout>

Step 5 :- Open MainActivity.java

package com.mapv2.demo;

import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends FragmentActivity {
   
    GoogleMap googleMap;
   

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        // Getting Google Play availability status
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

        // Showing status
        if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available

            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
            dialog.show();

        }else { // Google Play Services are available          

            // Getting reference to the SupportMapFragment of activity_main.xml
            SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

            // Getting GoogleMap object from the fragment
            googleMap = fm.getMap();

            // Enabling MyLocation Layer of Google Map
            googleMap.setMyLocationEnabled(true);
           
            // Setting click event handler for map
            googleMap.setOnMapClickListener(new OnMapClickListener() {
               
                @Override
                public void onMapClick(LatLng point) {
                    // Draw the marker at the taped position
                    drawMarker(point);
                }
            });
           
           
            // Setting click event handler for InfoWIndow
            googleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
               
                @Override
                public void onInfoWindowClick(Marker marker) {
                    // Remove the marker
                    marker.remove();                   
                }
            });           
        }
    }
   
   
    private void drawMarker(LatLng point){
        // Creating an instance of MarkerOptions
        MarkerOptions markerOptions = new MarkerOptions();

        // Setting latitude and longitude for the marker
        markerOptions.position(point);
       
        // Setting snippet for the InfoWindow
        markerOptions.snippet("Tap here to remove this marker");
       
        // Setting title for the InfoWindow
        markerOptions.title("Marker Demo");

        // Adding marker on the Google Map
        googleMap.addMarker(markerOptions);        
    }
   

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}


Step 6 :- Run Code.










Step 7 :- Download Code :-  https://dl.dropboxusercontent.com/u/109954727/Map/map25.zip

Storing and retrieving locations in SQLite from Google Maps Android API V2

Step 1 :- Create New Android Project.



Step 2 :- Add Google-play-services_lib to your project.

Step 3 :- Open AndroidManifest.xml file.

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />   
   
    <permission
          android:name="com.mapv2.demo.permission.MAPS_RECEIVE"
          android:protectionLevel="signature"/>

    <uses-permission android:name="com.mapv2.demo.permission.MAPS_RECEIVE"/>

    <uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
        <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    <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" >
        <activity
            android:name="com.mapv2.demo.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>
       
         <provider
            android:name="LocationsContentProvider"
            android:authorities="com.mapv2.demo.locations"
            android:exported="false" />
       
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyCmX7SLVHXxU9pSqb2QbAOvdnjAGUulOrk" />
       
    </application>
   
</manifest>

Step 4 :- Open activity_main.xml.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <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"/>
</RelativeLayout>

Step 5 :- Open MainActivity.java

package com.mapv2.demo;

import android.app.Dialog;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.Menu;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends FragmentActivity implements LoaderCallbacks<Cursor> {

    GoogleMap googleMap;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        // Getting Google Play availability status
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
       
        // Showing status
        if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available

            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
            dialog.show();

        }else { // Google Play Services are available           

            // Getting reference to the SupportMapFragment of activity_main.xml
            SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

            // Getting GoogleMap object from the fragment
            googleMap = fm.getMap();

            // Enabling MyLocation Layer of Google Map
            googleMap.setMyLocationEnabled(true);          
           
            // Invoke LoaderCallbacks to retrieve and draw already saved locations in map
            getSupportLoaderManager().initLoader(0, null, this);           
        }       
       
        googleMap.setOnMapClickListener(new OnMapClickListener() {
           
            @Override
            public void onMapClick(LatLng point) {       
               
                                   
                // Drawing marker on the map
                drawMarker(point);           
               
                // Creating an instance of ContentValues
                ContentValues contentValues = new ContentValues();
               
                // Setting latitude in ContentValues
                contentValues.put(LocationsDB.FIELD_LAT, point.latitude );
               
                // Setting longitude in ContentValues
                contentValues.put(LocationsDB.FIELD_LNG, point.longitude);
               
                // Setting zoom in ContentValues
                contentValues.put(LocationsDB.FIELD_ZOOM, googleMap.getCameraPosition().zoom);
               
                // Creating an instance of LocationInsertTask
                LocationInsertTask insertTask = new LocationInsertTask();
               
                // Storing the latitude, longitude and zoom level to SQLite database
                insertTask.execute(contentValues);               
                               
                Toast.makeText(getBaseContext(), "Marker is added to the Map", Toast.LENGTH_SHORT).show();                   
               
            }
        });   
       
       
        googleMap.setOnMapLongClickListener(new OnMapLongClickListener() {               
            @Override
            public void onMapLongClick(LatLng point) {
               
                // Removing all markers from the Google Map
                googleMap.clear();
               
                // Creating an instance of LocationDeleteTask
                LocationDeleteTask deleteTask = new LocationDeleteTask();
               
                // Deleting all the rows from SQLite database table
                deleteTask.execute();
               
                Toast.makeText(getBaseContext(), "All markers are removed", Toast.LENGTH_LONG).show();
                                               
            }
        });
    }
   
   
    private void drawMarker(LatLng point){
        // Creating an instance of MarkerOptions
        MarkerOptions markerOptions = new MarkerOptions();                   
           
        // Setting latitude and longitude for the marker
        markerOptions.position(point);
           
        // Adding marker on the Google Map
        googleMap.addMarker(markerOptions);           
    }
   
   
    private class LocationInsertTask extends AsyncTask<ContentValues, Void, Void>{
        @Override
        protected Void doInBackground(ContentValues... contentValues) {
           
            /** Setting up values to insert the clicked location into SQLite database */          
            getContentResolver().insert(LocationsContentProvider.CONTENT_URI, contentValues[0]);           
            return null;
        }       
    }
   
    private class LocationDeleteTask extends AsyncTask<Void, Void, Void>{
        @Override
        protected Void doInBackground(Void... params) {
           
            /** Deleting all the locations stored in SQLite database */
            getContentResolver().delete(LocationsContentProvider.CONTENT_URI, null, null);           
            return null;
        }       
    }   


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }


    @Override
    public Loader<Cursor> onCreateLoader(int arg0,
            Bundle arg1) {
       
        // Uri to the content provider LocationsContentProvider
        Uri uri = LocationsContentProvider.CONTENT_URI;
       
        // Fetches all the rows from locations table
        return new CursorLoader(this, uri, null, null, null, null);

    }


    @Override
    public void onLoadFinished(Loader<Cursor> arg0,
            Cursor arg1) {
        int locationCount = 0;
        double lat=0;
        double lng=0;
        float zoom=0;
       
        // Number of locations available in the SQLite database table
        locationCount = arg1.getCount();
       
        // Move the current record pointer to the first row of the table
        arg1.moveToFirst();
       
        for(int i=0;i<locationCount;i++){
           
            // Get the latitude
            lat = arg1.getDouble(arg1.getColumnIndex(LocationsDB.FIELD_LAT));
           
            // Get the longitude
            lng = arg1.getDouble(arg1.getColumnIndex(LocationsDB.FIELD_LNG));
           
            // Get the zoom level
            zoom = arg1.getFloat(arg1.getColumnIndex(LocationsDB.FIELD_ZOOM));
           
            // Creating an instance of LatLng to plot the location in Google Maps
            LatLng location = new LatLng(lat, lng);
           
            // Drawing the marker in the Google Maps
            drawMarker(location);
           
            // Traverse the pointer to the next row
            arg1.moveToNext();
        }
       
        if(locationCount>0){
            // Moving CameraPosition to last clicked position
            googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(lat,lng)));
           
            // Setting the zoom level in the map on last position  is clicked
            googleMap.animateCamera(CameraUpdateFactory.zoomTo(zoom)); 
           
        }       
    }
   
    @Override
    public void onLoaderReset(Loader<Cursor> arg0) {
        // TODO Auto-generated method stub       
    }   
}


1.)  LocationsDB.java


package com.mapv2.demo;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;


public class LocationsDB extends SQLiteOpenHelper{
   
    /** Database name */
    private static String DBNAME = "locationmarkersqlite";
   
    /** Version number of the database */
    private static int VERSION = 1;
   
    /** Field 1 of the table locations, which is the primary key */
    public static final String FIELD_ROW_ID = "_id";
   
    /** Field 2 of the table locations, stores the latitude */
    public static final String FIELD_LAT = "lat";
   
    /** Field 3 of the table locations, stores the longitude*/
    public static final String FIELD_LNG = "lng";
   
    /** Field 4 of the table locations, stores the zoom level of map*/
    public static final String FIELD_ZOOM = "zom";
   
    /** A constant, stores the the table name */
    private static final String DATABASE_TABLE = "locations";
   
    /** An instance variable for SQLiteDatabase */
    private SQLiteDatabase mDB; 
   

    /** Constructor */
    public LocationsDB(Context context) {
        super(context, DBNAME, null, VERSION);   
        this.mDB = getWritableDatabase();
    }
   

    /** This is a callback method, invoked when the method getReadableDatabase() / getWritableDatabase() is called
      * provided the database does not exists
    * */
    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql =     "create table " + DATABASE_TABLE + " ( " +
                            FIELD_ROW_ID + " integer primary key autoincrement , " +
                            FIELD_LNG + " double , " +
                            FIELD_LAT + " double , " +
                            FIELD_ZOOM + " text " +
                        " ) ";
                               
        db.execSQL(sql);
    }
   
    /** Inserts a new location to the table locations */
    public long insert(ContentValues contentValues){
        long rowID = mDB.insert(DATABASE_TABLE, null, contentValues);
        return rowID;
       
    }   
   
   
    /** Deletes all locations from the table */
    public int del(){
        int cnt = mDB.delete(DATABASE_TABLE, null , null);       
        return cnt;
    }
   
    /** Returns all the locations from the table */
    public Cursor getAllLocations(){
        return mDB.query(DATABASE_TABLE, new String[] { FIELD_ROW_ID,  FIELD_LAT , FIELD_LNG, FIELD_ZOOM } , null, null, null, null, null);
    }
   
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
       
    }

}



2.)  LocationsContentProvider.java




package com.mapv2.demo;

import java.sql.SQLException;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.net.Uri;

/** A custom Content Provider to do the database operations */
public class LocationsContentProvider extends ContentProvider{
   
    public static final String PROVIDER_NAME = "com.mapv2.demo.locations";
   
    /** A uri to do operations on locations table. A content provider is identified by its uri */
    public static final Uri CONTENT_URI = Uri.parse("content://" + PROVIDER_NAME + "/locations" );
   
    /** Constant to identify the requested operation */
    private static final int LOCATIONS = 1;   
   
    private static final UriMatcher uriMatcher ;
   
    static {
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        uriMatcher.addURI(PROVIDER_NAME, "locations", LOCATIONS);       
    }
   
    /** This content provider does the database operations by this object */
    LocationsDB mLocationsDB;
   
    /** A callback method which is invoked when the content provider is starting up */
    @Override
    public boolean onCreate() {
        mLocationsDB = new LocationsDB(getContext());
        return true;
    }
   
    /** A callback method which is invoked when insert operation is requested on this content provider */
    @Override
    public Uri insert(Uri uri, ContentValues values) {
        long rowID = mLocationsDB.insert(values);
        Uri _uri=null;
        if(rowID>0){
            _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
        }else {       
            try {
                throw new SQLException("Failed to insert : " + uri);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return _uri;   
    }
   
    @Override
    public int update(Uri uri, ContentValues values, String selection,
            String[] selectionArgs) {
        // TODO Auto-generated method stub
        return 0;
    }

   

    /** A callback method which is invoked when delete operation is requested on this content provider */
    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        int cnt = 0;       
        cnt = mLocationsDB.del();   
        return cnt;
    }
   
    /** A callback method which is invoked by default content uri */
    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {   
       
        if(uriMatcher.match(uri)==LOCATIONS){
            return mLocationsDB.getAllLocations();
        }
        return null;
    }

   
    @Override
    public String getType(Uri uri) {       
        return null;
    }   
}



Step 6 :- Run Code.




Step 7 :- Download Code :- https://dl.dropboxusercontent.com/u/109954727/Map/map24.zip