Headertab

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Saturday, 29 August 2015

GoogleMap use in Android Studio with fragment

Today i learn how to use google map in "Android Studio" with fragment.

Friends before start see the some important points.....like
1-Add googleplayservice dependecy.....

compile 'com.google.android.gms:play-services-maps:6.5.87'

2-Make sure install google paly service in SDK Manager


3-and last create a api key from https://console.developers.google.com/
 create a sha1 code....

For Eclipse

For Android Studio

keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android

copy and paste in cmd(Windows) or terminal(Mac) and get sh1 code like..



Create a new project and follow below instructions....


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

    <FrameLayout
        android:id="@+id/mycontainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true">

    </FrameLayout>

</RelativeLayout>
fragment_map.xml
<FrameLayout 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="com.example.samset.saralgoogle_map">
    <fragment
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.SupportMapFragment"
        android:id="@+id/map"
        />
</FrameLayout>
AndroidMainifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.samset.saralgoogle_map" >
    <permission
        android:name="com.example.samset.saralgoogle_map.fragment.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <uses-permission android:name="com.truiton.supportmapfragment.permission.MAPS_RECEIVE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <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" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/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>
        <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="YOUR API_KEY" />
    </application>

</manifest>

ActivityMain.java

public class MainActivity extends AppCompatActivity {
FragmentManager fragmentManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fragmentManager=getSupportFragmentManager();
        FragmentTransaction transaction=fragmentManager.beginTransaction();
        transaction.replace(R.id.mycontainer,new MapFragment());
        transaction.commit();

    }


}
MapFragment.java

public class MapFragment extends Fragment {

    public GoogleMap map;
    View view;
    UserLocation userLocation;

    public MapFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
            view=inflater.inflate(R.layout.fragment_map, container, false);

        map = ((SupportMapFragment)getChildFragmentManager().findFragmentById(R.id.map)).getMap();

            Log.e("Mymap"," Map is not null");
            userLocation=new UserLocation(getActivity());
            Location location=userLocation.getLocation();
            String Latlong=userLocation.updateWithNewLocation(location);
            map.addMarker(new MarkerOptions().position(new LatLng(location.getLatitude(), location.getLongitude())).title("Marker"));

        return view;
    }

}

UserLocation.java

public class UserLocation {
    Context context;
    LocationManager manager;
    Location location;

    boolean gps_enabled = false;
    boolean network_enabled = false;

    public UserLocation(Context ctx)
    {
        this.context=ctx;
    }


public Location getLocation()
{   String networkType;
    manager= (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
       networkType=check_gpsStatus(manager);
    Location location = manager.getLastKnownLocation(networkType);

    return location;
}
 public String check_gpsStatus(LocationManager locationManager)
 {
     String network = null;
     try {
         gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
         network = LocationManager.GPS_PROVIDER;
     } catch (Exception ex){}
     try {
         network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
         network=LocationManager.NETWORK_PROVIDER;

     } catch (Exception ex){ex.printStackTrace();}
     if ( !gps_enabled && !network_enabled ){
         AlertDialog.Builder dialog = new AlertDialog.Builder(context);
         dialog.setMessage("GPS not enabled");
         dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

             @Override
             public void onClick(DialogInterface dialog, int which) {
                 //this will navigate user to the device location settings screen
                 Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                 context.startActivity(intent);
             }
         });
         AlertDialog alert = dialog.create();
         alert.show();
     }

     return  network;
 }

See output...




No comments:

Post a Comment