Monday, 27 August 2018

How to Create Map and Show Current Location And Custom Location

Step 1:

AndroidStudio/New/MapActivity


activty_map.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_height="match_parent">
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorLiteGreen">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:gravity="center|left"
            android:orientation="horizontal">
            <ImageView
                android:id="@+id/im_arrow"
                android:layout_width="25dp"
                android:layout_height="20dp"
                android:background="@drawable/arrow_left"/>
            <ImageView
                android:layout_width="150dp"
                android:layout_height="30dp"
                android:layout_marginLeft="30dp"
                android:background="@drawable/logo_white"/>
        </LinearLayout>

    </android.support.v7.widget.Toolbar>
<fragment
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"
    tools:context="com.a2aonlinemart.MapsActivity" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:gravity="center"
        android:background="@color/colorLiteGreen">
        <Button
            android:id="@+id/but_loc"
            android:layout_width="200dp"
            android:layout_height="match_parent"
            android:text="Location"
            android:background="@color/colorAccent"/>
    </LinearLayout>
</LinearLayout>


Step 2:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    LocationManager locationManager;
    ImageView im_arrow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        im_arrow = (ImageView) findViewById(R.id.im_arrow);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        if(locationManager.isProviderEnabled(locationManager.NETWORK_PROVIDER)){
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    double latitute=location.getLatitude();
                    double longitude=location.getLongitude();
                    LatLng latLng=new LatLng(latitute,longitude);
                    Geocoder geocoder=new Geocoder(getApplicationContext());
                    try {
                        List<Address> arList=geocoder.getFromLocation(latitute,longitude, 1);
                        String str=arList.get(0).getLocality()+" , ";
                        str+=arList.get(0).getCountryName();


                        mMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.
                                defaultMarker(BitmapDescriptorFactory.HUE_AZURE)).title(str));

                        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10.2f));


                        //another mark
                        LatLng la1 = new LatLng(9.9252,78.1198);
                        LatLng la2 = new LatLng(13.0827,80.2707);
                        LatLng la3 = new LatLng(11.0168,76.9558);

                        List<Address> arList2=geocoder.getFromLocation(9.9252,78.1198, 1);
                        String str2=arList2.get(0).getLocality()+" , ";
                        str2+=arList.get(0).getCountryName();
                        mMap.addMarker(new MarkerOptions().position(la1).title(str2));

                        List<Address> arList3=geocoder.getFromLocation(13.0827,80.2707, 1);
                        String str3=arList3.get(0).getLocality()+" , ";
                        str3+=arList.get(0).getCountryName();
                        mMap.addMarker(new MarkerOptions().position(la2).title(str3));

                        List<Address> arList4=geocoder.getFromLocation(11.0168,76.9558, 1);
                        String str4=arList4.get(0).getLocality()+" , ";
                        str4+=arList.get(0).getCountryName();
                        mMap.addMarker(new MarkerOptions().position(la3).title(str4));

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onStatusChanged(String provider, int status, Bundle extras) {

                }

                @Override
                public void onProviderEnabled(String provider) {

                }

                @Override
                public void onProviderDisabled(String provider) {

                }
            });
        }
        else if (locationManager.isProviderEnabled(locationManager.GPS_PROVIDER)){
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    double latitute=location.getLatitude();
                    double longitude=location.getLongitude();
                    LatLng latLng=new LatLng(latitute,longitude);
                    Geocoder geocoder=new Geocoder(getApplicationContext());
                    try {
                        List<Address> arList=geocoder.getFromLocation(latitute,longitude, 1);
                        String str=arList.get(0).getLocality()+", ";
                        str+=arList.get(0).getCountryName();
                        mMap.addMarker(new MarkerOptions().position(latLng).title(str));
                        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10.2f));

                        //another mark
                        LatLng la1 = new LatLng(15.664861, 77.134940);
                        LatLng la2 = new LatLng(9.816625, 77.811000);
                        LatLng la3 = new LatLng(8.454931, 77.708947);
                        mMap.addMarker(new MarkerOptions().position(la1).title("Hello World"));
                        mMap.addMarker(new MarkerOptions().position(la2).title("Hello World"));
                        mMap.addMarker(new MarkerOptions().position(la3).title("Hello World"));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onStatusChanged(String provider, int status, Bundle extras) {

                }

                @Override
                public void onProviderEnabled(String provider) {

                }

                @Override
                public void onProviderDisabled(String provider) {

                }
            });

        }


        im_arrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

       /* LatLng la1 = new LatLng(15.664861, 77.134940);
        LatLng la2 = new LatLng(9.816625, 77.811000);
        LatLng la3 = new LatLng(8.454931, 77.708947);
        mMap.addMarker(new MarkerOptions().position(la1).title("Hello World"));
        mMap.addMarker(new MarkerOptions().position(la2).title("Hello World"));
        mMap.addMarker(new MarkerOptions().position(la3).title("Hello World"));*/
       /* mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney2));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney3));*/

    }}


Step :3

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

    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme.NoActionBar">

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Step 4:

Insert your Map Access Key

res/values/google_map_api.xml

<resources>
    <!--    TODO: Before you run your application, you need a Google Maps API key.

    To get one, follow this link, follow the directions and press "Create" at the end:
    https://console.developers.google.com/flows/enableapi?apiid=maps_android_backend&keyType=CLIENT_SIDE_ANDROID&r=A7:4B:CD:47:43:E0:79:1B:22:30:C8:EE:D9:C0:40:5A:B8:B9:AA:F6%3Bcom.a2aonlinemart
    You can also add your credentials to an existing key, using these values:
    Package name:    A7:4B:CD:47:43:E0:79:1B:22:30:C8:EE:D9:C0:40:5A:B8:B9:AA:F6
    SHA-1 certificate fingerprint:    A7:4B:CD:47:43:E0:79:1B:22:30:C8:EE:D9:C0:40:5A:B8:B9:AA:F6
    Alternatively, follow the directions here:    https://developers.google.com/maps/documentation/android/start#get-key
    Once you have your key (it starts with "AIza"), replace the "google_maps_key" 
   string in this file.    -->   
 <string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">
       xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx   <<<google map access key>>>
    </string>
</resources>





Blue Mark My Current Location
Red Mark Custom Location

No comments:

Post a Comment

HOW TO CREATE CIRCLE IMAGE VIEW

Step 1: implementation 'de.hdodenhof:circleimageview:3.0.0' Step 2: <de.hdodenhof.circleimageview.CircleImageView xmlns:ap...