Friday, 14 November 2014

Map V2 Example

create application and import google-play-services library.

create 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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.diyamap.act.MainActivity" >

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

</RelativeLayout>


and below is my menifest.xml file

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

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="19"/>

    <permission
        android:name="com.diyamap.act.permission.MAPS_RECEIVE"
        android:protectionLevel="signature"/>

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

<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"/>
<!-- The following two permissions are not required to use
     Google Maps Android API v2, but are recommended. -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="com.diyamap.act.permission.MAPS_RECEIVE" />

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <uses-library android:name="com.google.android.maps"/>

        <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="AIzaSyDg11tWv7QEaQOFxzdD44O-C3ts11jxW_s" />
            </application>
</manifest>

here is MainActivity.java

package com.examplemap.act;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.StreetViewPanorama;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.GroundOverlayOptions;
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 map;
Drawable drawable;
Context mContext;
protected String latitude, longitude;
protected boolean gps_enabled, network_enabled;
// Double lat,lon;
MarkerOptions marker;
String lat,lon;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
mContext = MainActivity.this;
Utility.registerLocationListener(mContext);
lat = Utility.getSharedKey("Latitude", mContext);
lon = Utility.getSharedKey("Longitude", mContext);
map.clear();

// Creating an instance of MarkerOptions
marker = new MarkerOptions();
LatLng latlng = new LatLng(Double.parseDouble(lat),
Double.parseDouble(lon));

marker = new MarkerOptions().position(latlng).title("Hello Maps").snippet("Population: 4,137,400");

// Draw  ground overlay 
/*GroundOverlayOptions newarkMap = new GroundOverlayOptions()
        .image(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE))
        .position(latlng, 8600f, 6500f);
map.addGroundOverlay(newarkMap);*/

// Custom Marker Icon

/*
* fromAsset(String assetName) – Loading from assets folder fromBitmap
* (Bitmap image) – Loading bitmap image fromFile (String path) –
* Loading from file fromResource (int resourceId) – Loading from
* drawable resource
*/
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));

map.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(Double.parseDouble(lat), Double
.parseDouble(lon))).zoom(12).build();

map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

// Changing Map Type
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
// map.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
// map.setMapType(GoogleMap.MAP_TYPE_NONE);

// Showing Current Location
map.setMyLocationEnabled(true); // false to disable

// Zooming Buttons
map.getUiSettings().setZoomControlsEnabled(true); // true to enable

// Zooming Functionality
map.getUiSettings().setZoomGesturesEnabled(true);

// Compass Functionality
map.getUiSettings().setCompassEnabled(true);

// My Location Button
map.getUiSettings().setMyLocationButtonEnabled(true);

// Map Rotate Gesture
map.getUiSettings().setRotateGesturesEnabled(true);
}
}

create Utility.java for common function define here

package com.examplemap.act;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

@SuppressLint("SimpleDateFormat")
public class Utility {
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager manager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
return info != null;
}
public static void setSharedKey(String key, String value, Context context) {
SharedPreferences spre = context.getSharedPreferences(
context.getPackageName(), Context.MODE_PRIVATE);
SharedPreferences.Editor prefEditor = spre.edit();
prefEditor.putString(key, value);
//prefEditor.clear();
prefEditor.commit();
}
public static String getSharedKey(String key, Context context) {
SharedPreferences spre = context.getSharedPreferences(
context.getPackageName(), Context.MODE_PRIVATE);
return spre.getString(key, "");
}
public static AlertDialog myAlertDialog;
  public static void showDialogwithTitle(Context context,String message) {

         AlertDialog.Builder builder = new AlertDialog.Builder(context);
         //builder.setTitle(context.getResources().getString(R.string.app_name));
         builder.setMessage(message);
         builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                 public void onClick(DialogInterface dialog, int arg1) {
                     dialog.dismiss();
                 }});
         builder.setCancelable(false);
         myAlertDialog = builder.create();
         myAlertDialog.show();
 }
  
  
public static void registerLocationListener(Context context) {
LocationManager lManager = null;
CurrentLocListener cListener = null;
lManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
cListener = new CurrentLocListener(context);
boolean isGpsEnabled = false;
boolean isNetworkEnabled = false;
isGpsEnabled = lManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = lManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isGpsEnabled) {
lManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
cListener);
Location location = lManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
Utility.setSharedKey("Latitude",
String.valueOf(location.getLatitude()), context);
Utility.setSharedKey("Longitude",
String.valueOf(location.getLongitude()), context);
}
}
if (isNetworkEnabled) {
lManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
0, 0, cListener);
Location location = lManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
Utility.setSharedKey("Latitude",
String.valueOf(location.getLatitude()), context);
Utility.setSharedKey("Longitude",
String.valueOf(location.getLongitude()), context);
}
}
}
}

then create CurrentLocListener.java

package com.examplemap.act;


import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.util.Log;

public class CurrentLocListener implements LocationListener {
private static final String TAG = "CurrentLocListener - ";
public static final String ACTION_LOCATION_CHANGED = "tixe.act.ACTION_LOCATION_CHANGED";
Context mContext;
String latitude,longitude,token;
public CurrentLocListener(Context context){
Log.i(TAG, TAG + "CurrentLocListener - ");
mContext = context;
}

@Override
public void onLocationChanged(Location location) {
Log.i(TAG, TAG + "onLocationChanged - Latitude: " + String.valueOf(location.getLatitude()) + " Longitude: " + String.valueOf(location.getLongitude()));
Utility.setSharedKey("Latitude", String.valueOf(location.getLatitude()), mContext);
Utility.setSharedKey("Longitude", String.valueOf(location.getLongitude()), mContext);
Intent mIntent = new Intent(ACTION_LOCATION_CHANGED);
mContext.sendBroadcast(mIntent);
}

@Override
public void onProviderDisabled(String provider) {
Log.i(TAG, TAG + "onProviderDisabled - ");
}

@Override
public void onProviderEnabled(String provider) {
Log.i(TAG, TAG + "onProviderEnabled - ");
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.i(TAG, TAG + "onStatusChanged - ");
}
}

Now,

for get API key go to https://console.developers.google.com ,and create project over there , then in that project go to APIs & auth tab and Enable google maps android v2 and go to next Credential tab and there create Public API access ,and click on Create new key , and click on Android key  here we need SHA1 key


For getting SHA1 key open terminal and write below command

keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore -list -v
password : android

it will create SHA1 key

use that key in api console project for create Androidkey

put there SHA1key;yourandroidapppackagename
and click on create button it creates API key for map.

your code is ready to run.



No comments:

Post a Comment

Comments

Find Hours Diffrence in Kotlin

  In Kotlin, determining the difference in hours between two timestamps is a common task, especially in scenarios involving time-based calcu...