Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

マップの表示 #26

Open
wants to merge 14 commits into
base: master
Choose a base branch
from
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,4 @@ gradlew
gradlew.bat
local.properties
/build
*.apk
*.apk
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

なんの差分?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

あんまり意味なさげだから,上げない方がいいかも

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

了解しました

2 changes: 1 addition & 1 deletion app/.gitignore
Original file line number Diff line number Diff line change
@@ -1 +1 @@
/build
/build
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

同上

4 changes: 3 additions & 1 deletion app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ android {
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
manifestPlaceholders = [API_KEY: System.getenv("API_KEY")]
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

APIKEYを隠すのはGood!!

}
buildTypes {
release {
Expand All @@ -25,10 +26,11 @@ android {

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.core:core-ktx:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.android.gms:play-services-maps:16.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
Expand Down
24 changes: 24 additions & 0 deletions app/src/debug/res/values/google_maps_api.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<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=DF:33:9C:AE:13:E3:2D:FC:53:99:11:F7:30:0F:81:22:E1:E2:A6:01%3Bcom.example.kanazawaapp_2019

You can also add your credentials to an existing key, using these values:

Package name:
DF:33:9C:AE:13:E3:2D:FC:53:99:11:F7:30:0F:81:22:E1:E2:A6:01

SHA-1 certificate fingerprint:
DF:33:9C:AE:13:E3:2D:FC:53:99:11:F7:30:0F:81:22:E1:E2:A6:01

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">Your Api Key</string>
</resources>
34 changes: 29 additions & 5 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,46 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.kanazawaapp_2019">

<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

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

<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="${API_KEY}" />
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

API_KEY管理ちゃんとできてるのgoodです 👍


<activity
android:name=".FirstDescriptionActivity"
android:theme="@style/Theme.AppCompat.Light.NoActionBar">
android:name=".ShelterActivity"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".FirstDescriptionActivity"
android:theme="@style/Theme.AppCompat.Light.NoActionBar">
</activity>

</application>

</manifest>
501 changes: 501 additions & 0 deletions app/src/main/assets/shisetsu_hinan.csv

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class FirstDescriptionActivity : AppCompatActivity() {
}

fun toNext(view: View) {
val intent = Intent(this, SecondDescriptionActivity::class.java)
// val intent = Intent(this, SecondDescriptionActivity::class.java)
startActivity(intent)
//遷移するアニメーションを定義
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left)
Expand Down
228 changes: 228 additions & 0 deletions app/src/main/java/com/example/kanazawaapp_2019/ShelterActivity.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,228 @@
package com.example.kanazawaapp_2019

import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
// import androidx.core.content.getSystemService
import android.provider.Settings
import android.view.Window
import android.widget.Toast
import androidx.appcompat.widget.Toolbar

import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
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.MarkerOptions
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.IOException
import java.util.jar.Manifest


class ShelterActivity : AppCompatActivity(), OnMapReadyCallback, LocationListener {

private lateinit var gMap: GoogleMap
var column: Array<String> = emptyArray()
var shelters: Array<ShelterData> = emptyArray()

var currentLatitude: Double=0.toDouble()
var currentLongitude: Double=0.toDouble()

val PERMISSION_CODE = 1000

lateinit var locationManager: LocationManager

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_shelter)
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
val mapFragment = supportFragmentManager
.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)

setSupportActionBar(findViewById(R.id.shelterToolbar))
window.statusBarColor = ContextCompat.getColor(this, R.color.colorPrimaryDark)

fetchCsv("shisetsu_hinan.csv")

/*パーミッションがあるか確認*/
if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

こっちもクラッシュする?

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

初回マップ表示時(GPSの使用許可がない状態)で現在地を取得しようとすると、エラーで起動できません。
そのため、どうしてもここで一度確認をしなければなりませんでした。

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

この前に現在地取得のメソッド走らせたらどー?

// なかった場合はリクエストする
ActivityCompat.requestPermissions(this,
arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION), PERMISSION_CODE)
}else{
// あった場合は現在地を取得する
locationStart()

if(::locationManager.isInitialized){
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
1000,
15f,
this
)
}
}
}

/* 現在地取得処理 */
fun locationStart() {

locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager

val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager

if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Log.d("debug", "location manager Enabled")
} else {
// to prompt setting up GPS
val settingsIntent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
startActivity(settingsIntent)
Log.d("debug", "not gpsEnable, startActivity")
}

if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Comment on lines +95 to +96
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

上でpermission確認しているのに,ここでもやる意味は?

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

これがないとなぜかクラッシュしてしまいます

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

なるほど

ActivityCompat.requestPermissions(this,
arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION), 1000)

Log.d("debug", "checkSelfPermission false")
return
}

locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
1000,
50f,
this)
}

/*パーミッションリクエスト後の処理*/
override fun onRequestPermissionsResult(
requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
if (requestCode == PERMISSION_CODE) {
// 使用が許可された
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d("debug", "checkSelfPermission true")
setUpMap()
locationStart()

} else {
// それでも拒否された時
val toast = Toast.makeText(this,
"これ以上なにもできません", Toast.LENGTH_SHORT)
toast.show()
}
}
}

override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {
/* API 29以降非推奨
when (status) {
LocationProvider.AVAILABLE ->
Log.d("debug", "LocationProvider.AVAILABLE")
LocationProvider.OUT_OF_SERVICE ->
Log.d("debug", "LocationProvider.OUT_OF_SERVICE")
LocationProvider.TEMPORARILY_UNAVAILABLE ->
Log.d("debug", "LocationProvider.TEMPORARILY_UNAVAILABLE")
}
*/
}

override fun onLocationChanged(location: Location) {
currentLatitude = location.latitude
currentLongitude = location.longitude
Log.d("debug", "${currentLongitude}")
Log.d("debug", "${currentLatitude}")
}

override fun onProviderEnabled(provider: String) {

}

override fun onProviderDisabled(provider: String) {

}

/* csvの処理 */
fun fetchCsv(fileName: String) {
try{
val file = resources.assets.open(fileName)
val fileReader = BufferedReader(InputStreamReader(file))
var i: Int = 0
fileReader.forEachLine {
if(it.isNotBlank()) {
if(i == 0) {
column = it.split(",").toTypedArray()
}else{
val line = it.split(",").toTypedArray()
shaping(line)
}
}
i++;
}
}catch (e: IOException) {
//例外処理
print(e)
}
}

fun shaping(line: Array<String>){
var name = line[10]
var latitude = line[2]
var longitude = line[3]


val shelter = ShelterData(
name = name,
latitude = latitude,
longitude = longitude
)
shelters += shelter
}

fun mappingMarker(shelters: Array<ShelterData>) {
for(i in shelters) {
val lat = i.latitude?.toDouble()
val lon = i.longitude?.toDouble()
val location = LatLng(lat!!, lon!!)
gMap.addMarker(MarkerOptions().position(location))
}
}

fun setUpMap() {
gMap.isMyLocationEnabled = true
gMap.uiSettings.isMyLocationButtonEnabled = true
}

/* mapの処理 */
override fun onMapReady(googleMap: GoogleMap) {
gMap = googleMap
mappingMarker(shelters)

gMap.uiSettings.isZoomControlsEnabled = true

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
return
}else{
// パーミッションがない場合にこの処理をするとクラッシュする
setUpMap()
}
}

val kanazawa = LatLng(36.561031, 136.656647)
gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(kanazawa, 16f))
}
}
7 changes: 7 additions & 0 deletions app/src/main/java/com/example/kanazawaapp_2019/ShelterData.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.example.kanazawaapp_2019

data class ShelterData (
var name: String? = null,
var latitude: String? = null,
var longitude: String? = null
)
1 change: 1 addition & 0 deletions app/src/main/res/layout/.gitkeep
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
this file keep layoutFolder
28 changes: 28 additions & 0 deletions app/src/main/res/layout/activity_shelter.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?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="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical"
tools:context=".ShelterActivity">

<androidx.appcompat.widget.Toolbar
android:id="@+id/shelterToolbar"
android:minHeight="?attr/actionBarSize"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
app:titleTextColor="@color/colorWhite"
app:title="@string/shelterHeaderTitle"/>

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ShelterActivity" />
</LinearLayout>
1 change: 1 addition & 0 deletions app/src/main/res/values/colors.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@
<color name="colorPrimary">#F2B451</color>
<color name="colorPrimaryDark">#CE8321</color>
<color name="colorAccent">#D81B60</color>
<color name="colorWhite">#FFFFFF</color>
</resources>
Loading