티스토리 뷰
컨트롤 알트 S를 눌러서 설정으로 간 다음
Google play Service를 활성화.
컨트롤 알트 쉬프트 에스를 눌러서
프로젝트 구조에서 app -> Dependencies -> +
play-service 로 검색하면 maps달린거 추가.
메니페스트
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.acid.samplelocation">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"/>
<permission
android:name="com.example.acid.samplelocation.permission.MAPS.RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.acid.samplelocation.permission.MAPS_RECEIVE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICE" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<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">
<uses-library android:name="com.google.android.maps"/>
<meta-data android:name="com.google.android.maps.v2.API_KEY"
android:value="API키를 넣으면 된다."/>
<meta-data android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version"/>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
구글 Api key는 구글에서 구하면 된다.
layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GPS location"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GPS ON"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView1" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GPS OFF"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button" />
<Button
android:id="@+id/buttonMap"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="버튼" />
</LinearLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<fragment
android:id="@+id/map"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
</LinearLayout>
package com.example.acid.samplelocation;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdate;
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.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
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 AppCompatActivity {
TextView textView;
Button button;
Button button2;
Button buttonMap;
SupportMapFragment mapFragment;
GoogleMap map;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView1);
button = findViewById(R.id.button);
button2 = findViewById(R.id.button2);
//버튼 맵
buttonMap = findViewById(R.id.buttonMap);
//지도 객체 참조
mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
//최초 표시 부분
//없으면 지도가 회색으로 나온다.
// 서울역으로
googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(37.555744, 126.970431)));
//지도 Zoom 정도
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
});
//지도 인식
MapsInitializer.initialize(this);
buttonMap.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
requestMylocation();
}
});
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
requestMylocation();
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
stopLocation();
Toast.makeText(getApplicationContext(), "GPS OFF", Toast.LENGTH_LONG).show();
}
});
}
//class가 아닌 pricate 값으로 하나 만든다. remove를 위해서
private LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
Double latitude = location.getLatitude();
Double longitude = location.getLongitude();
showCurrentLocation(latitude, longitude);
}
public void showCurrentLocation(Double getLatitude, Double getLongitude) {
LatLng latLng = new LatLng(getLatitude, getLongitude);
map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17));
//마커로 좌표 찍기
MarkerOptions marker = new MarkerOptions();
//마커에 넣을 정보
//snippet은 subtitle같은 것이다
marker.position(latLng).title("My position").snippet("my position");
//마커를 지도에 표기
map.addMarker(marker).showInfoWindow();
//마커를 누르면 실행되는 것
map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker) {
Toast.makeText(getApplicationContext(), "클릭했음", Toast.LENGTH_LONG).show();
return false;
}
});
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
};
LocationManager locationManager = null;
//내 위치 요청
public void requestMylocation() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); //LOCATION_SERVICE
Location location = null;
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { //네트워크가 활성화 되어 있다면
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
} else {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); //마지막에 알려진 위치
}
String getLongitude = "LAST getLongitude : " + location.getLongitude();
String getLatitude = " LAST getLatitude : " + location.getLatitude();
Log.i("Location ", getLongitude + "" + getLatitude);
Double longitude = location.getLongitude();
Double latitude = location.getLatitude();
textView.setText("latitude " + latitude);
Toast.makeText(getApplicationContext(), "GPS", Toast.LENGTH_LONG).show();
long minTime = 10000; // 10초
long minDistance = 0;
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, minDistance, locationListener);
}
//GPS중단
public void stopLocation() {
locationManager.removeUpdates(locationListener);
}
}
주석으로 설명은 달아놓았는데, GPS받는 부분에서 구글 맵 부분이 추가된 형태이다.
'프로그래밍 > 안드로이드' 카테고리의 다른 글
[안드로이드] 비디오 재생 +seekbar로 음량조절 (0) | 2018.10.15 |
---|---|
[안드로이드] 간단한 음악 플레이어 (0) | 2018.10.15 |
[안드로이드] GPS 수신과 종료 (0) | 2018.10.14 |
[안드로이드] Url에 요청해서 Json 받아오기2 (JSON 요청과 outputstream 요청) (0) | 2018.10.11 |
[안드로이드] Url에 요청해서 Json 받아오기 (Get) (0) | 2018.10.10 |