Featured post

Marshmallow Features Point by Point

Android Runtime (“ART”) Improved application performance and lower memory overhead for faster  multi-tasking. Battery Doze...

Monday 15 February 2016

Display multiple markers on map | zoom level to show all the markers | Associate an object with Marker Google MapV2 in Android

his article aims to give knowledge about how to implements newer Google Maps into your applications. If you have already worked with V1, implementing V2 is very easy.

Here are the few implementation for this article.

1) Plot multiple pin on Google map
2) Zoom level to show all the markers within screen
3) Click event on marker associated object item.
4) Customize info window on Google map,Please visit.

Before starting implementation Google map with your application, you need follow few step to create api key for map. follow this link to set up your Google play service and map api key.




Step 1 : Create activity_main.xml

<LinearLayout 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"
    android:orientation="vertical" >

    <RelativeLayout
        android:id="@+id/rlMapLayout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1.2"
        android:orientation="vertical" >

        <fragment
            android:id="@+id/map"
            android:name="com.google.android.gms.maps.SupportMapFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </RelativeLayout>


</LinearLayout>

Step 2 : Create class as LatLngBean

public class LatLngBean
{     
       private String Title="";
       private String Snippet="";
       private String Latitude="";
       private String  Longitude="";
      
       public String getTitle() {
              return Title;
       }
       public void setTitle(String title) {
              Title = title;
       }
       public String getSnippet() {
              return Snippet;
       }
       public void setSnippet(String snippet) {
              Snippet = snippet;
       }
       public String getLatitude() {
              return Latitude;
       }
       public void setLatitude(String latitude) {
              Latitude = latitude;
       }
       public String getLongitude() {
              return Longitude;
       }
       public void setLongitude(String longitude) {
              Longitude = longitude;
       }
      

}

Step 3 : Create class as MainActivity

import java.util.ArrayList;
import java.util.HashMap;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.RelativeLayout;
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.OnInfoWindowClickListener;
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.LatLngBounds;
import com.google.android.gms.maps.model.LatLngBounds.Builder;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends FragmentActivity {

       private GoogleMap googleMap;
       private ArrayList<LatLng>listLatLng;
       private RelativeLayout rlMapLayout;
       HashMap<Marker,LatLngBean> hashMapMarker = new HashMap<Marker,LatLngBean>();
      
       @Override
       protected void onCreate(Bundle savedInstanceState)
       {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
             
              rlMapLayout=(RelativeLayout) findViewById(R.id.rlMapLayout);
             
              setUpMapIfNeeded();       
              setData();
             
       }

       private void setData()
       {
              ArrayList<LatLngBean> arrayList=new ArrayList<LatLngBean>();
              LatLngBean bean=new LatLngBean();
              bean.setTitle("Ahmedabad");
              bean.setSnippet("Hello,Ahmedabad");
              bean.setLatitude("23.0300");
              bean.setLongitude("72.5800");
              arrayList.add(bean);
             
              LatLngBean bean1=new LatLngBean();
              bean1.setTitle("Surat");
              bean1.setSnippet("Hello,Surat");
              bean1.setLatitude("21.1700");
              bean1.setLongitude("72.8300");          
              arrayList.add(bean1);
             
              LatLngBean bean2=new LatLngBean();
              bean2.setTitle("Vadodara");
              bean2.setSnippet("Hello,Vadodara");
              bean2.setLatitude("22.3000");
              bean2.setLongitude("73.2000");          
              arrayList.add(bean2);
             
              LoadingGoogleMap(arrayList);
       }

       /**
        * @author Hasmukh Bhadani
        * Set googleMap if require
        */
       private void setUpMapIfNeeded()
       {
              int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

              // Google Play Services are not available
              if(status!=ConnectionResult.SUCCESS)
              {
                     int requestCode = 10;
                     Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status,this, requestCode);
                     dialog.show();

              }
              else
              {
                     if (googleMap == null)
                     {
                           googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
                           if (googleMap != null)
                           {
                                  googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                                  googleMap.setMyLocationEnabled(true);
                                 googleMap.getUiSettings().setMyLocationButtonEnabled(true);
                                 googleMap.getUiSettings().setZoomControlsEnabled(true);
                           }
                     }
              }
       }

       /**
        * @author Hasmukh Bhadani
        * Loading Data to the GoogleMap
        */
       // -------------------------Google Map
       void LoadingGoogleMap(ArrayList<LatLngBean> arrayList)
       {     
              if (googleMap != null)
              {
                     googleMap.clear();
                     googleMap.getUiSettings().setMyLocationButtonEnabled(true);
                     googleMap.setMyLocationEnabled(true);
                     googleMap.getUiSettings().setZoomControlsEnabled(true);

                     if(arrayList.size()>0)
                     {                                
                           try
                           {                         
                                  listLatLng=new ArrayList<LatLng>();
                                  for (int i = 0; i < arrayList.size(); i++)
                                  {
                                         LatLngBean bean=arrayList.get(i);
                                         if(bean.getLatitude().length()>0 && bean.getLongitude().length()>0)
                                         {
                                                doublelat=Double.parseDouble(bean.getLatitude());
                                                doublelon=Double.parseDouble(bean.getLongitude());          
                                               
                                                Marker marker =googleMap.addMarker(new MarkerOptions()
                                                .position(new LatLng(lat,lon))
                                                .title(bean.getTitle())
                                                .snippet(bean.getSnippet())
                                                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
                                               
                                                //Add Marker to Hashmap
                                                hashMapMarker.put(marker,bean);

                                                //Set Zoom Level of Map pin
                                                LatLng object=new LatLng(lat, lon);
                                                listLatLng.add(object);
                                         }                                
                                  }
                                  SetZoomlevel(listLatLng);
                           }
                           catch (NumberFormatException e)
                           {
                                  e.printStackTrace();
                           }
                          
                           googleMap.setOnInfoWindowClickListener(newOnInfoWindowClickListener() {
                                 
                                  @Override
                                  public void onInfoWindowClick(Marker position)
                                  {
                                         LatLngBean bean=hashMapMarker.get(position);
                                         Toast.makeText(getApplicationContext(), bean.getTitle(),Toast.LENGTH_SHORT).show();
                                        
                                  }
                           });
                     }
              }

              else
              {
                     Toast.makeText(getApplicationContext(),"Sorry! unable to create maps", Toast.LENGTH_SHORT).show();
              }
       }
       /**
        * @author Hasmukh Bhadani
        * Set Zoom level all pin withing screen on GoogleMap
        */
       public void  SetZoomlevel(ArrayList<LatLng> listLatLng)
       {
              if (listLatLng != null && listLatLng.size() == 1)
              {
                    googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(listLatLng.get(0), 10));
              }
              else if (listLatLng != null && listLatLng.size() > 1)
              {
                     final Builder builder = LatLngBounds.builder();
                     for (int i = 0; i < listLatLng.size(); i++)
                     {
                           builder.include(listLatLng.get(i));
                     }

                     final ViewTreeObserver treeObserver =rlMapLayout.getViewTreeObserver();
                     treeObserver.addOnGlobalLayoutListener(newOnGlobalLayoutListener()
                     {
                           @SuppressWarnings("deprecation")
                           @Override
                           public void onGlobalLayout()
                           {
                                  if(googleMap != null){
                                        googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), findViewById(R.id.map)
                                                       .getWidth(), findViewById(R.id.map).getHeight(), 80));
                                        rlMapLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                                  }
                           }
                     });

              }
       }

}

Step 4 : Modify AndroidManifest.xml

 -  you need to modify your AndroidManifest.xml for set few permission for Google map,

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />
   
     <!-- MAP PERMISSION -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permissionandroid:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />   

    <permission
        android:name="<YOUR PCAKAGENAME>.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <uses-permission android:name="<YOUR PCAKAGENAME>.permission.MAPS_RECEIVE" />

  <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=".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>       
          <!-- MAP meta-data -->
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="<YOUR API KEY HERE...>" />
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
       
    </application>
</manifest>

For More reference follow link

Google map operation visit 

No comments:

Post a Comment