Notice
Recent Posts
Recent Comments
Today
Total
04-29 04:14
Archives
관리 메뉴

Jeongchul Kim

Google Map API App 및 Activity 생성 본문

Android

Google Map API App 및 Activity 생성

김 정출 2016. 1. 26. 10:54

Google Map API App 및 Activity생성

제가 만들 프로그램은 레이아웃에 구글맵을 띄우고

시작과 종료 버튼을 생성합니다. 옆에 Timer는 시작버튼을 누른 시점 부터 타이머와 같이 시간(초단위)을 표시합니다.

종료 버튼을 누르면 타이머가 멈춥니다.

또한 시작버튼을 누름에 따라 1초 간격으로 자신의 위치를 빨간색 원으로 표시해주며,

PolyLine을 이용하여 이후의 1초와의 원과 직선을 이어 자신의 경로를 나타냅니다.

밑의 사진은 스크린 샷입니다.

패키지에 우선 클래스 파일 2개가 필요합니다. (GpsInfo, MapsActivity)

레이아웃에는 activity_maps.xml 파일이 필요합니다.


GpsInfo 클래스 소스코드 입니다.


package sincere.kimjungchul.myapplication;

import android.app.AlertDialog;

import android.app.Service;

import android.content.Context;

import android.content.DialogInterface;

import android.content.Intent;

import android.location.Location;

import android.location.LocationListener;

import android.location.LocationManager;

import android.os.Bundle;

import android.os.IBinder;

import android.provider.Settings;

import android.util.Log;

import android.widget.Toast;


public class GpsInfo extends Service implements LocationListener {


  private final Context mContext;


  // 현재 GPS 사용유무

  boolean isGPSEnabled = false;


  // 네트워크 사용유무

  boolean isNetworkEnabled = false;


  // GPS 상태값

  boolean isGetLocation = false;


  Location location;

  double lat; // 위도

  double lon; // 경도


  // GPS 정보 업데이트 거리 10미터

  private static final long MIN_DISTANCE_UPDATES = 10;


  // GPS 정보 업데이트 시간 1/1000

  private static final long MIN_TIME_UPDATES = 1000 * 60 * 1;


  protected LocationManager locationManager;


  public GpsInfo(Context context) {

      this.mContext = context;

      getLocation();

  }


  public Location getLocation() {

      try {

          locationManager = (LocationManager) mContext

                  .getSystemService(LOCATION_SERVICE);


          isGPSEnabled = locationManager

                  .isProviderEnabled(LocationManager.GPS_PROVIDER);

          Log.d("GPS Enabled?","::"+isGPSEnabled);


          isNetworkEnabled = locationManager

                  .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

          if(!isGPSEnabled) {

              showSettingsAlert();

          }

          if (!isGPSEnabled && !isNetworkEnabled) {


          } else {

              this.isGetLocation = true;

              if (isNetworkEnabled) {

                  locationManager.requestLocationUpdates(

                          LocationManager.NETWORK_PROVIDER,

                          MIN_TIME_UPDATES,

                          MIN_DISTANCE_UPDATES, this);


                  if (locationManager != null) {

                      location = locationManager

                              .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                      if (location != null) {

                          // 위도 경도 저장

                          lat = location.getLatitude();

                          lon = location.getLongitude();

                      }

                  }

              }

              if (isGPSEnabled) {

                  if (location == null) {

                      locationManager

                              .requestLocationUpdates(

                                      LocationManager.GPS_PROVIDER,

                                      MIN_TIME_UPDATES,

                                      MIN_DISTANCE_UPDATES,

                                      this);

                      if (locationManager != null) {

                          location = locationManager

                                  .getLastKnownLocation(LocationManager.GPS_PROVIDER);

                          if (location != null) {

                              lat = location.getLatitude();

                              lon = location.getLongitude();

                          }

                      }

                  }

              }

          }


      } catch (Exception e) {

          e.printStackTrace();

      }

      return location;

  }


  /**

   * GPS 종료

   * */

  public void stopUsingGPS() {

      if (locationManager != null) {

          locationManager.removeUpdates(GpsInfo.this);

      }

  }


  /**

   * 위도값

   * */

  public double getLatitude() {

      if (location != null) {

          lat = location.getLatitude();

      }

      return lat;

  }

  /**

   * 경도값

   * */

  public double getLongitude() {

      if (location != null) {

          lon = location.getLongitude();

      }

      return lon;

  }


  public boolean isGetLocation() {

      return this.isGetLocation;

  }


  /**

   * GPS 정보를 가져오지 못했을때 설정값으로 갈지 물어보는 alert 창

   * */

  public void showSettingsAlert() {

      AlertDialog.Builder alertDialog = new AlertDialog.Builder(

              mContext);


      alertDialog.setTitle("GPS 사용유무셋팅");

      alertDialog

              .setMessage("GPS 셋팅이 되지 않았을수도 있습니다.\n 설정창으로 가시겠습니까?");


      alertDialog.setPositiveButton("Settings",

              new DialogInterface.OnClickListener() {

                  public void onClick(DialogInterface dialog,

                                      int which) {

                      Intent intent = new Intent(

                              Settings.ACTION_LOCATION_SOURCE_SETTINGS);

                      mContext.startActivity(intent);

                  }

              });

      alertDialog.setNegativeButton("Cancel",

              new DialogInterface.OnClickListener() {

                  public void onClick(DialogInterface dialog,

                                      int which) {

                      dialog.cancel();

                  }

              });


      alertDialog.show();

  }


  @Override

  public IBinder onBind(Intent arg0) {

      return null;

  }


  public void onLocationChanged(Location location) {

      // TODO Auto-generated method stub


  }


  public void onStatusChanged(String provider, int status,

                              Bundle extras) {

      // TODO Auto-generated method stub


  }


  public void onProviderEnabled(String provider) {

      // TODO Auto-generated method stub


  }


  public void onProviderDisabled(String provider) {

      // TODO Auto-generated method stub


  }

}


MapsActivity 소스 코드입니다.


package sincere.kimjungchul.myapplication;


import android.graphics.Point;

import android.os.Handler;

import android.os.Message;

import android.support.v4.app.FragmentActivity;

import android.os.Bundle;

import android.support.v4.app.FragmentManager;

import android.util.Log;

import android.view.View;

import android.widget.Button;

import android.widget.TextView;


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

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

import com.google.android.gms.maps.model.PolylineOptions;



public class MapsActivity extends FragmentActivity implements GoogleMap.OnMapClickListener {


  private int timer = 0;

  private GoogleMap mMap;

  private LatLng ex_point;

  private LatLng current_point;

  private boolean isInit = false;

  Handler handler;


  @Override

  protected void onCreate(Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);

      setContentView(R.layout.activity_maps);

      // BitmapDescriptorFactory 생성하기 위한 소스

      MapsInitializer.initialize(getApplicationContext());

      FragmentManager myFragmentManager = getSupportFragmentManager();

      SupportMapFragment mySupportMapFragment

              = (SupportMapFragment)myFragmentManager.findFragmentById(R.id.map);

      mMap = mySupportMapFragment.getMap();

      ex_point = new LatLng(0,0);

      current_point = new LatLng(0,0);

      final Button btn_start = (Button)this.findViewById(R.id.btn_start);

      final Button btn_finish = (Button)this.findViewById(R.id.btn_finish);


      init();

      mMap.setOnMapClickListener(this);

      btn_start.setOnClickListener(new View.OnClickListener() {

          @Override

          public void onClick(View view) {

              if (view.getId() == R.id.btn_start) {

                  handler = new Handler() {

                      @Override

                      public void handleMessage(Message msg) {

                          handler.sendEmptyMessageDelayed(0, 1000);

                          TextView tv = (TextView)findViewById(R.id.tv_timer);

                          timer++;

                          tv.setText("Timer : "+timer);


                          GpsInfo gps = new GpsInfo(MapsActivity.this);

                          // GPS 사용유무 가져오기

                          if (gps.isGetLocation()) {

                              Log.d("GPS사용", "찍힘");

                              double latitude = gps.getLatitude();

                              double longitude = gps.getLongitude();

                              // 현재 화면에 찍힌 포인트로 부터 위도와 경도를 알려준다.

                              LatLng latLng = new LatLng(latitude, longitude);

                              // Showing the current location in Google Map

                              mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));


                              // Map 을 zoom 합니다.

                              mMap.animateCamera(CameraUpdateFactory.zoomTo(15));


                              current_point = latLng;

                              mMap.addPolyline(new PolylineOptions().color(0xFFFF0000).width(30.0f).geodesic(true).add(latLng).add(ex_point));

                              ex_point = latLng;


                              // 마커 설정.

                              MarkerOptions optFirst = new MarkerOptions();

                              optFirst.alpha(0.5f);

                              optFirst.anchor(0.5f, 0.5f);

                              optFirst.position(latLng);// 위도 • 경도

                              optFirst.title("Current Position");// 제목 미리보기

                              optFirst.snippet("Snippet");

                              optFirst.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker));

                              mMap.addMarker(optFirst).showInfoWindow();

                          }



                      }

                  };

                  handler.sendEmptyMessage(0);

              }


          }

      });


      btn_finish.setOnClickListener(new View.OnClickListener() {

          @Override

          public void onClick(View view) {

              if(view.getId() == R.id.btn_finish) {

                  handler.removeMessages(0);

              }

          }

      });

  }

  /** Map 클릭시 터치 이벤트 */

  public void onMapClick(LatLng point) {

      /* GPS가 켜지지 않은 상태로 앱이켜지면 init()이 안되어 초기 ex_point값이 0,0 이를 해결*/

      if(!isInit)

          init();


      Log.d("터치 이벤트", "터치");

      // 현재 위도와 경도에서 화면 포인트를 알려준다

      Point screenPt = mMap.getProjection().toScreenLocation(point);

      GpsInfo gps = new GpsInfo(MapsActivity.this);

      // GPS 사용유무 가져오기

      if (gps.isGetLocation()) {

          Log.d("GPS사용","찍힘");

          double latitude = gps.getLatitude();

          double longitude = gps.getLongitude();

          // 현재 화면에 찍힌 포인트로 부터 위도와 경도를 알려준다.

          LatLng latLng = new LatLng(latitude, longitude);

          // Showing the current location in Google Map

          mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));


          // Map 을 zoom 합니다.

          mMap.animateCamera(CameraUpdateFactory.zoomTo(15));


          current_point = latLng;

          mMap.addPolyline(new PolylineOptions().color(0xFFFF0000).width(30.0f).geodesic(true).add(latLng).add(ex_point));

          ex_point = latLng;


          Log.d("맵좌표", "좌표: 위도(" + String.valueOf(point.latitude) + "), 경도("

                  + String.valueOf(point.longitude) + ")");

          Log.d("화면좌표", "화면좌표: X(" + String.valueOf(screenPt.x) + "), Y("

                  + String.valueOf(screenPt.y) + ")");



          // 마커 설정.

          MarkerOptions optFirst = new MarkerOptions();

          optFirst.alpha(0.5f);

          optFirst.anchor(0.5f,0.5f);

          optFirst.position(latLng);// 위도 • 경도

          optFirst.title("Current Position");// 제목 미리보기

          optFirst.snippet("Snippet");

          optFirst.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker));

          mMap.addMarker(optFirst).showInfoWindow();

      }


  }


  /**

   * 초기화

   * @author

   */

  private void init() {


      GooglePlayServicesUtil.isGooglePlayServicesAvailable(MapsActivity.this);

      GoogleMap mGoogleMap = ((SupportMapFragment) getSupportFragmentManager()

              .findFragmentById(R.id.map)).getMap();


      GpsInfo gps = new GpsInfo(MapsActivity.this);

      //gps.getLocation();

      // GPS 사용유무 가져오기

      if (gps.isGetLocation()) {

          double latitude = gps.getLatitude();

          double longitude = gps.getLongitude();


          // Creating a LatLng object for the current location

          LatLng latLng = new LatLng(37.28,126.97243608534338);

          //LatLng latLng = new LatLng(latitude, longitude);

          ex_point = latLng;


          // Showing the current location in Google Map

          mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));


          // Map 을 zoom 합니다.

          mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(13));


          // 마커 설정.

          MarkerOptions optFirst = new MarkerOptions();

          optFirst.alpha(0.5f);

          optFirst.anchor(0.5f,0.5f);

          optFirst.position(latLng);// 위도 • 경도

          optFirst.title("Start");// 제목 미리보기

          optFirst.snippet("Snippet");

          optFirst.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker));

          mMap.addMarker(optFirst).showInfoWindow();


          isInit = true;

      }

  }

}


다음은 activity_maps.xml 소스 코드 내용입니다.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:background="#fff"

android:orientation="vertical" >


  <fragment

      android:id="@+id/map"

      android:name="com.google.android.gms.maps.SupportMapFragment"

      class="com.google.android.gms.maps.SupportMapFragment"

      android:layout_width="match_parent"

      android:layout_height="match_parent">

  </fragment>

  <LinearLayout

      android:layout_width="match_parent"

      android:layout_height="wrap_content"

      android:orientation="horizontal">

      <Button

          android:id="@+id/btn_start"

          android:layout_width="100dp"

          android:layout_height="50dp"

          android:text="시작"/>

      <Button

          android:id="@+id/btn_finish"

          android:layout_width="100dp"

          android:layout_height="50dp"

          android:text="종료"/>

      <TextView

          android:layout_gravity="center"

          android:gravity="center"

          android:layout_width="wrap_content"

          android:layout_height="wrap_content"

          android:id="@+id/tv_timer"

          android:text="1"

          android:textSize="20sp"/>

  </LinearLayout>



</RelativeLayout>


추가로

res/drawable에 marker.png가 필요합니다.




Comments