Showing posts with label Android code sample: MapFragment. Show all posts
Showing posts with label Android code sample: MapFragment. Show all posts

Sunday, January 27, 2013

Create MapFragment and GoogleMap using Java code

In previous exercises, MapFragment and SupportMapFragment are defined in XML of layout file. We can create it using Java code, without XML.

package com.example.androidmapsv2;

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.MapFragment;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends Activity {
 
 final int RQS_GooglePlayServices = 1;
 private GoogleMap myMap;
 MapFragment myMapFragment;
 private static final String TAG_MYMAPFRAGMENT = "TAG_MyMapFragment";

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

  FragmentManager myFragmentManager = getFragmentManager();
  myMapFragment = 
    (MapFragment)myFragmentManager.findFragmentByTag(TAG_MYMAPFRAGMENT);
  
  if(myMapFragment == null){
   myMapFragment = MapFragment.newInstance();
   FragmentTransaction fragmentTransaction = myFragmentManager.beginTransaction();
   fragmentTransaction.add(android.R.id.content, myMapFragment, TAG_MYMAPFRAGMENT);
   fragmentTransaction.commit();
  }

 }

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

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
  
  switch (item.getItemId()) {
  case R.id.menu_legalnotices:
   String LicenseInfo = GooglePlayServicesUtil.getOpenSourceSoftwareLicenseInfo(
     getApplicationContext());
   AlertDialog.Builder LicenseDialog = new AlertDialog.Builder(MainActivity.this);
   LicenseDialog.setTitle("Legal Notices");
   LicenseDialog.setMessage(LicenseInfo);
   LicenseDialog.show();
   return true; 
  }
  return super.onOptionsItemSelected(item);
 }

 @Override
 protected void onResume() {
  super.onResume();
  
  int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
  if (resultCode == ConnectionResult.SUCCESS){
   Toast.makeText(getApplicationContext(), 
     "isGooglePlayServicesAvailable SUCCESS", 
     Toast.LENGTH_LONG).show();
   
   if(myMap == null){
    myMap = myMapFragment.getMap();
    if(myMap != null){
     myMap.setMyLocationEnabled(true);
     myMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
    }else{
     Toast.makeText(getApplicationContext(), 
       "cannot getMap!", 
       Toast.LENGTH_LONG).show();
    }
   }
   
  }else{
   GooglePlayServicesUtil.getErrorDialog(resultCode, this, RQS_GooglePlayServices); 
  }
 }

}

Create MapFragment and GoogleMap using Java code


download filesDownload the files.

The series:
A simple example using Google Maps Android API v2, step by step.

Wednesday, January 2, 2013

Using MapFragment instead of SupportMapFragment

In previous exercises of "A simple example using Google Maps Android API v2", I embedded fragment of SupportMapFragment. In this exercise, I change back to MapFragment instead of SupportMapFragment. Such that we can compare the difference between them.

Using MapFragment instead of SupportMapFragment


First of all, to use com.google.android.gms.maps.MapFragment, we have to modify AndroidManifest.xml to change android:minSdkVersion to "11".
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.androidmapsv2"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="16" />
    
    <permission 
        android:name="com.example.androidmapsv2.permission.MAPS_RECEIVE" 
        android:protectionLevel="signature"></permission>
    <uses-permission 
        android:name="com.example.androidmapsv2.permission.MAPS_RECEIVE"/>
    <uses-permission 
        android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <uses-permission 
        android:name="android.permission.INTERNET"/>
    <uses-permission 
        android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <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" >
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyBD9fsiMd_G9Pzeq2Eqas2FwJjzMGbSOnA"/>
        <activity
            android:name="com.example.androidmapsv2.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>
    </application>

</manifest>


Modify /res/layout/activity_main.xml to include fragment of class "com.google.android.gms.maps.MapFragment".
<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"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/locinfo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.MapFragment"/>

</LinearLayout>


Finally, modify main code, MainActivity.java extends Activity instead of FragmentActivity, also update the imports from com.google.android.gms.maps.SupportMapFragment to com.google.android.gms.maps.MapFragment, android.support.v4.app.FragmentManager to android.app.FragmentManager.
package com.example.androidmapsv2;

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.MapFragment;
//import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.model.LatLng;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.location.Location;
import android.os.Bundle;
//import android.support.v4.app.FragmentActivity;
//import android.support.v4.app.FragmentManager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnMapClickListener{
 
 final int RQS_GooglePlayServices = 1;
 private GoogleMap myMap;
 
 Location myLocation;
 TextView tvLocInfo;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  tvLocInfo = (TextView)findViewById(R.id.locinfo);
  
  FragmentManager myFragmentManager = getFragmentManager();
  MapFragment myMapFragment 
   = (MapFragment)myFragmentManager.findFragmentById(R.id.map);
  myMap = myMapFragment.getMap();
  
  myMap.setMyLocationEnabled(true);
  
  myMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
  //myMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
  //myMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
  //myMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
  
  myMap.setOnMapClickListener(this);
  

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

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
  switch (item.getItemId()) {
     case R.id.menu_legalnotices:
      String LicenseInfo = GooglePlayServicesUtil.getOpenSourceSoftwareLicenseInfo(
        getApplicationContext());
      AlertDialog.Builder LicenseDialog = new AlertDialog.Builder(MainActivity.this);
      LicenseDialog.setTitle("Legal Notices");
      LicenseDialog.setMessage(LicenseInfo);
      LicenseDialog.show();
         return true;
     }
  return super.onOptionsItemSelected(item);
 }

 @Override
 protected void onResume() {
  // TODO Auto-generated method stub
  super.onResume();

  int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
  
  if (resultCode == ConnectionResult.SUCCESS){
   Toast.makeText(getApplicationContext(), 
     "isGooglePlayServicesAvailable SUCCESS", 
     Toast.LENGTH_LONG).show();
  }else{
   GooglePlayServicesUtil.getErrorDialog(resultCode, this, RQS_GooglePlayServices);
  }
  
 }

 @Override
 public void onMapClick(LatLng point) {
  tvLocInfo.setText(point.toString());
  myMap.animateCamera(CameraUpdateFactory.newLatLng(point));
 }

}


download filesDownload the files.

The series:
A simple example using Google Maps Android API v2, step by step.

Saturday, December 29, 2012

Get GoogleMap from MapFragment/SupportMapFragment

To get the GoogleMap underlying MapFragment/SupportMapFragment, using getMap() method.

Example to acquire GoogleMap underlying MapFragment/SupportMapFragment.
   FragmentManager myFragmentManager = getSupportFragmentManager();
   SupportMapFragment mySupportMapFragment 
    = (SupportMapFragment)myFragmentManager.findFragmentById(R.id.map);
   myMap = mySupportMapFragment.getMap();




Modify Java code from last exercise "Check if correct Google Play Service available for Google Maps Android API v2.
package com.example.androidmapsv2;

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.SupportMapFragment;

import android.app.AlertDialog;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends FragmentActivity {
 
 final int RQS_GooglePlayServices = 1;
 private GoogleMap myMap;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
   FragmentManager myFragmentManager = getSupportFragmentManager();
   SupportMapFragment mySupportMapFragment 
    = (SupportMapFragment)myFragmentManager.findFragmentById(R.id.map);
   myMap = mySupportMapFragment.getMap();

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

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
  switch (item.getItemId()) {
     case R.id.menu_legalnotices:
      String LicenseInfo = GooglePlayServicesUtil.getOpenSourceSoftwareLicenseInfo(
        getApplicationContext());
      AlertDialog.Builder LicenseDialog = new AlertDialog.Builder(MainActivity.this);
      LicenseDialog.setTitle("Legal Notices");
      LicenseDialog.setMessage(LicenseInfo);
      LicenseDialog.show();
         return true;
     }
  return super.onOptionsItemSelected(item);
 }

 @Override
 protected void onResume() {
  // TODO Auto-generated method stub
  super.onResume();

  int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
  
  if (resultCode == ConnectionResult.SUCCESS){
   Toast.makeText(getApplicationContext(), 
     "isGooglePlayServicesAvailable SUCCESS", 
     Toast.LENGTH_LONG).show();
  }else{
   GooglePlayServicesUtil.getErrorDialog(resultCode, this, RQS_GooglePlayServices);
  }
  
 }

}


Also correct the layout (a TextView is mis-placed in former version!).
<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
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.SupportMapFragment"/>

</RelativeLayout>


download filesDownload the files.

Next:
- Display my location on Google Maps Android API v2


The series:
A simple example using Google Maps Android API v2, step by step.