요즘엔 웹 작업을 안하니 쓸모 없는 기능이지만 가끔 똑같은걸 물어보는 사람이 있다 보니 사용법을 만들게 되었습니다.

 

작업순서

1. 이미지 불러오기

2. 신규 Layer 만들기

3. 이미지 작업

4. 저장

 

 

1. 이미지 불러오기

 

포토샵을 실행하고 작업하려는 이미지를 불러 옵니다.

File > Open



탐색기가 나오면 파일을 선택 하고 열기를 합니다.



파일이 열리면 Marquee Tool(점선 네모)을 이용해 작업하려는 비행기를 선택 합니다.



비행기만 남기기 위해 나머지는 잘라버려야 겠죠?

Image > Crop

메뉴를 이용하여 비행기 이외에는 모두 삭제 합니다.



네 이제 비행기만 남았네요.



지금 잘라내고 남은 비행기는 아직 일반 이미지 입니다.


 

2. 신규 Layer 만들기

 

Layers를 보면 그냥 Background 라고 하나만 있습니다.



여기에 실제로 필요한 투명 레이어를 하나 생성 합니다.

휴지통 옆에 있는 아이콘이 레이어 생성 버튼입니다.



Background라는 레이어 위에 Layer1이 추가 되었습니다.

앞쪽 붓 모양과 파란색이 현재 선택된 레이어 입니다.

Layer1에는 아무것도 없기 때문에 다시 원본이미지로 이동해야 합니다.

이동 방법은 아래 Background를 클릭하면 됩니다.




3. 이미지 작업

 

이제 이미지 작업을 시작 합니다.

 

요술막대 도구를 이용하여 흰색 배경을 선택 합니다.

그림 배경이 복잡한 경우 지우개를 이용해서 지워야 하는 경우도 있습니다.


photoshop 투명 이미지


지금은 하얀 배경이 선택 되어있는 상태이고 이제는 비행기가 선택되도록 해야 합니다.

 

Select > Inverse

메뉴를 이용해 비행기가 선택 되도록 합니다.

 


비행기만 선택이 되어있습니다.



여기서 Ctrl + C를 이용하여 비행기를 복사 합니다.

그리고 Layer1으로 이동하고 Ctrl + V로 붙여 넣기 합니다.

이제 Layer1에도 비행기가 들어 있습니다.



Background는 필요가 없어졌으니 눈 표시를 클릭해서 안보이도록 합니다.



투명 이미지가 되었습니다.


 

4. 저장

 

이제 사용할 수 있도록 저장만 하면 되겠군요.

 

File > Save As

메뉴를 선택 합니다.


저장할 Format과 파일이름을 입력하고 저장 버튼을 클릭 합니다.



Indexed Color 창이 나타납니다.

Forced는 Web을 선택 합니다.



옵션은 기본 Normal로 두고 OK를 클릭 합니다.



이제 투명한 이미지로 저장이 되었습니다.


- copy coding -


티스토리 사이드 바에 애드센스 광고를 추가해 봅니다.

 

작업 순서는 다음과 같습니다.

1. 플러그인 설치

2. 사이드바 편집

3. 애드센스 광고 생성

4. 사이드 광고 적용


3번을 맨 처음에 해도 관계없습니다.


일반 광고와 동일하게 진행이 됩니다.


google adsense sidebar


 

1. 플러그인 설치


tistory에 로그인 하고 관리 페이지 좌측 메뉴에서 플러그인을 선택 합니다.



그리고 우측에 플러그인 리스트들이 있는데 아래로 쭉 내리면서 배너출력을 찾습니다.



배너출력을 클릭해 주면

적용여부 팝업 창이 나옵니다.



적용 버튼을 클릭 합니다.

 

그러면 배너출력이 사용중으로 변경되며 상단으로 올라 옵니다.



 

사용하지 않으려면 다시 배터출력을 클릭해서 해지 하면 됩니다.


 

2. 사이드바 편집

 

이제 추가한 배너출력의 위치를 편집 합니다.

 

좌측메뉴에서

꾸미기 > 사이드바

를 선택 합니다.

 


기본모듈에 보이지 않던 배너출력 모듈이 2개가 생겼습니다.

 

여기에서 HTML 배너출력의 우측 +기호를 선택합니다.



우측 사이드바1 상단으로 이동 됩니다.

사이드바 광고를 맨위에 있는건 보기 않좋아 아래로 내려봅니다.



앞부분을 눌러 위치를 이동하고 편집을 클릭 합니다.

그러면 사이드바 광고를 삽입할 수 있습니다.



이제 이곳 입력란에 애드센스 광고를 넣어주면 됩니다.

여기까지 해놓고 광고를 만들러 갑니다.



3. 애드센스 광고 생성

 

구글 애드센스에 접속합니다.

광고단위 > 새 광고 단위를 선택 합니다.






텍스트 및 디스플레이 광고를 선택 합니다.

이름만 적어주고 나머지는 기본값을 그대로 사용합니다.



광고크기를 설정 안해도 저절로 맞춰집니다.

저장 및 코드 생성 버튼을 클릭 합니다.

코드 생성 팝업 창이 나옵니다.



중간에 있는 광고 코드를 복사 합니다.

이제 복사한 코드를 적용만 하면 됩니다.

 


4. 사이드 광고 적용

 

다시 티스토리로 돌아와서

 

복사한 광고 스크립트를 붙여넣기 합니다.



이름은 보기 편하게 적어주고

복사해온 코드를 HTML소스에 복사 한 후 확인 버튼을 클릭합니다.



배너출력이라는 문구가 변경이 되어있네요.

 

변경사항 저장을 클릭 합니다.

이제 기다림만 남았습니다.

 

저는 메뉴가 좌측에 있어서 좌측에 애드센스 광고가 나타납니다.



생각보다 크네요. 멋도 없고...

고민되네.


- copy coding -



가까운 친척 중의 한 사람이 돼지를 몰고 오는 꿈 해몽
 -> 직계가족 중의 한 사람이 가까운 시일 내에 돈을 가져온다.

한가운데 돼지가 빠져 허우적거리는 꿈 해몽
 -> 사업에서 방해자가 나타나며, 명예도 실추될 조짐이다.특히 물건을 잃어버릴 운세이다.

다른 집의 우리에서 어미와 새끼돼지를 모두 자기 집으로 데려오는 꿈 해몽
 -> 사업이 번창하고 모두가 부러워할 명분이 생긴다.특히 혼인이나 복권 등으로 인해 기쁜 소식이 있을 징조이다.

돼지 머리를 올려놓고 고사상을 차리는 꿈 해몽
 -> 소원이 성취되고 건강은 호전된다.

돼지 한 마리가 갑자기 여러 마리로 변하는 꿈 해몽

 -> 재물이 생기며 사업이 번창한다.연구하는 직업을 가진 사람은 좋은 결실을 맺게 된다.

돼지가 공중에서 자기를 향해 떨어져서 돼지에 깔려 혼이 난 꿈 해몽
 -> 무심코 한 행동이나 기대하지 않은 사업에서 의외의 좋은 결과를 보게 된다.

돼지가 논이나 밭엉망으로 만드는 꿈 해몽
 -> 부동산으로 인한 손재수가 있고, 주위의 일로 인하여 해를 입게 될 수도 있다.

돼지가 똥통에 빠져 허우적거리는 것을 구해 주는 꿈 해몽
 -> 명예운·재물운 등의 운이 트이는 형상의 길몽이다.

돼지가 무서워서 달아나는 꿈 해몽
 -> 가까운 사람의 불상사나 손재수를 함께 겪게 되는 징조이다.

돼지가 방 안이나 집 안으로 들어 오는 꿈 해몽
 -> 태몽이라면 높은 지위에 오르고 부귀를 누릴 자식을 얻게 될 길몽이다.

돼지가 병들어 신음하고 있는 꿈 해몽
 -> 공연한 일로 인해 구설수에 오른다.어린이는 특히 물과 불에 조심해야 한다.

돼지가 사람으로 변하는 꿈 해몽
 -> 관사에 손재수가 발생하여 손해를 보게 된다.

돼지가 새끼를 낳는 꿈 해몽
 -> 가만히 있어도 재산이 늘어나며 사업은 연속적으로 이득이 발생하고 회사는 번창하게 된다.

돼지가 자신을 따라오는 꿈 해몽
 -> 시험은 좋은 결과를 얻고 좋은 직장이 생기고 재물도 따라 온다.

돼지가 집 밖으로 도망가는데 잡지 못하고 놓치는 꿈 해몽
 -> 일의 성과를 제대로 간수못해서 모든 것이 헛수고가 될 것이다.

돼지가 쫓아오거나 자신을 끌어안는 꿈 해몽
 -> 승진운이나 취업운이 들어오는 길몽이다.명예를 얻을 수도 있다.

돼지고기를 먹은 꿈 해몽
 -> 따분하고 답답한 일에 종사하게 된다.

돼지고기를 상식 이상으로 많이 사는 꿈 해몽
 -> 뜻하지 않은 많은 재물을 얻게 된다.

돼지들끼리 서로 싸우거나 자신이 돼지와 같이 생활하는 꿈 해몽
 -> 사업이나 가정에 좋은 변화가 일어날 징조이다.금전과 관련해서는 부자가 될 운세이다.

돼지들이 교미하는 꿈 해몽
 -> 현재 하는 일이 크게 성공할 것을 알려 주는 꿈이다.

돼지떼가 나타나 길을 막는 꿈 해몽
 -> 횡재할 꿈으로 복권을 사거나 경마장에 가는 것이 좋다.

돼지를 가득 실은 수레나 트럭을 운전하는 꿈 해몽
 -> 일에서 책임지는 권리를 얻게 되거나 기관으로부터 포상을 받을 징조이다.또는 자본을 활용하여 높은 부가가치를 창출하게 된다.

돼지를 붙잡아 매는 꿈 해몽
 -> 조력자를 만나 일이 잘 풀릴 징조이며, 또는 집안에 호흡이 잘 맞는 사람을 불러 들이게 된다.

돼지를 사다가 잡아서 파는 꿈 해몽
 -> 재물을 잃거나 다른 사람에게 주게 된다.

돼지를 아무리 쫓아도 자꾸 따라오는 꿈 해몽
 -> 투자에서 재미를 못 보는 운세이다.


돼지 복권 꿈 해몽



돼지를 우리에 가두는 꿈 해몽
 -> 금전적으로는 아주 좋은 꿈으로 재물을 거두어 곳간에 챙기는 형국이다.

돼지를 죽이려고 넘어뜨려 놓는 꿈 해몽
 -> 생각하고 있는 어떤 일이나 사업이 크게 번창할 것을 말한다.

돼지를 줄지어 세우고 걸어가는 꿈 해몽
 -> 오랜만에 반가운 소식을 접하거나 손님이 찾아올 조짐이다.

돼지를 차에 가득하게 실어다 우리에 넣은 꿈 해몽
 -> 뜻하지 않은 재물이 들어온다.

돼지를 통째로 삶거나 구워서 칼로 잘라 먹는 꿈 해몽
 -> 단체생활에서 주도권을 잡게 되거나 난제가 해결되면서 활기를 띨 징조이다.

돼지를 파는 꿈 해몽
 -> 자기 소유의 물건을 잃어버리거나 남에게 일거리를 빼앗기게 된다.

돼지를 팔고 있는 꿈 해몽
 -> 잘못된 판단으로 다른 사람 좋은 일을 시키거나 손해를 볼 것이다.

돼지를 팔러 가는 꿈 해몽
 -> 손재를 당할 징조로, 보증을 서거나 계를 하면 손해를 보게 된다.집안에서는 남편이나 아내에게 근심이 생긴다.

돼지머리를 삶아서 칼로 썰어 그 일부를 감추어둔 꿈 해몽
 -> 사업상 장부를 위조해 세금의 일부를 급한 곳에 활용할 수도 있다.

돼지머리를 제삿상에 올려 놓는 꿈 해몽
 -> 자신의 작품 등을 제 3자에게 칭찬 받거나 누군가에게 물질적인 보답을 받게 된다.

돼지새끼를 사는 꿈 해몽
 -> 적은 돈을 얻지만 그 돈을 이용하여 큰 재물을 만들 수 있다.

돼지새끼를 쓰다듬은 후 아이를 낳은 꿈 해몽
 -> 이것이 태몽이라면 재물이 많은 자식을 낳겠지만 그 자식으로 인해서 마음고생을 한다.

돼지와 방에서 싸우다 돼지의 목을 누르는 꿈 해몽
 -> 사업을 일으키거나 재물을 소유하며 경쟁, 재판 등의 시비가 있으나 승리한다.

돼지우리에서 소변을 보는데 돼지새끼 들이 한꺼번에 몰려와서 받아먹는 꿈 해몽
 -> 여러 작품을 유명인에 의해서 평가 받게 된다.

돼지의 엉덩이를 칼로 찌르고 목을 쳐서 죽인 꿈 해몽
 -> 무슨 일을 하는데 시작은 잘 했으면서도 결과가 신통치 않다.

돼지의 크기와 수표가 정비례한 꿈 해몽
 -> 재물이 생기게 된다.

돼지의 을 몽땅 깎아버리는 꿈 해몽
 -> 집안 식구 중에 운세가 좋지 않은 사람이 생기게 된다.특히 손재·시비·소송 등과 시험에 실패할 운세이다.

맹수 이상으로 사나운 돼지가 갑자기 방에서 사람으로 변하는 꿈 해몽
 -> 상대하는 사람의 겉과 속이 다를 수 있다.돼지를 차에 싣고 오거나 등에 지거나 몰고 오는 꿈 

멧돼지 등 사나운 동물의 꿈 해몽
 -> 일반적으로 나쁜 운을 뜻한다.

멧돼지 수십 마리가 한꺼번에 몰려오는 꿈 해몽
 -> 직계가족, 일가친척 중에 자식을 낳은 사람이 있으면 그 자손의 앞날은 밝다.

멧돼지가 사람을 물려고 덤벼드는 것을 죽인 꿈 해몽
 -> 힘들고 어려운 일이나, 적의 침입을 막을 수 있다.

멧돼지가 집에 쳐들어와 난장판을 만드는 꿈 해몽
 -> 과중한 업무나 감당할 수 없는 부채가 있을 경우 이런 꿈을 꾸게 된다.

멧돼지를 잡는 꿈 해몽
 -> 대학입학, 고시합격, 권리확보 등이 뜻대로 성사된다.

멧돼지를 쫓거나 쫓기는 꿈 해몽
 -> 일상생활에서 비참한 실망을 뜻한다.

멧돼지에게 자신이 살해당하는 꿈 해몽
 -> 가까운 시일 안에 승진할 가능성이 매우 크다.

복스럽게 생긴 새끼돼지를 쓰다듬는 꿈 해몽
 -> 사업이 번창하고 특히 이사를 하면 좋을 징조이다.태몽이라면 부자가 될 자손을 보게 된다.

새끼돼지 여러 마리를 마당에 풀어 놓는 꿈 해몽
 -> 재물이나 이권 등이 들어오지만, 결국은 모두 다 잃어버리는 운세이다.

새끼돼지를 쓰다듬는 꿈 해몽
 -> 어떤 사람으로 인해 마음고생할 일이 생길 것이다.

새끼돼지를 품에 끌어 안는 꿈 해몽
 -> 태몽이라면 재물복이 많은 자식을 얻게 된다.

야생 수퇘지가 진흙 속에서 뒹굴고 있는 것을 보는 꿈 해몽
 -> 돈을 벌 수 있는 새로운 기회가 기다리고 있다는 암시로, 특히 더럽혀지지 않은 깨끗한 모습이었다면 예상외의 성공을 기대할 수 있다.

야생 수퇘지의 꿈 해몽
 -> 누군가의 시기를 받고 있으며, 심하면 악의에 찬 소문에 휩싸인다.

여러 가지 색깔의 돼지새끼 들이 태어나는 것을 보고 출산한 꿈 해몽
 -> 직계가족 중에서 이별을 하거나 자손들이 제각기 다른 사업에 손을 대게 된다.

여러 마리의 돼지를 보는 꿈 해몽
 -> 음식이나 의복 등의 재물이나 이권이 생길 길몽이다.

여러 마리의 돼지새끼를 낳아 그 돼지가 자라서 우리 안에 가득 찬 꿈 해몽
 -> 부동산이나 증권 등에 투자한 돈이 몇 배로 불어날 조짐이 있다.

우물이나 똥더미에 빠진 돼지를 끄집어 내는 꿈 해몽
 -> 투자하는 것마다 큰 이익을 보며 장사나 사업이 잘 되고 하는 일마다 이득을 보게 된다.

자기가 돼지가 되는 꿈 해몽
 -> 자기가 큰 부자가 되어서 안락하게 살아 갈 좋은 꿈이다.

자신에게 돼지가 덤벼들어 상처를 입는 꿈 해몽
 -> 안과 밖이 다른 사람이 자신의 재물이나 업적을 노리고 있다는 주의이다.

자신의 얼굴을 돼지가 발톱으로 할퀴는 꿈 해몽
 -> 사람을 잘못 만나 큰 낭패를 볼 징조이다.계약·광고·사채 등으로 인한 손실이 예상된다.

자신이 돼지우리에 들어가 돼지와 같이 생활하는 꿈 해몽
 -> 재물이 많이 들어와 엄청난 부자가 되고 부유한 생활을 하게 된다.

주인 없는 돼지를 길에서 잡아다가 자기 집 우리에 가두는 꿈 해몽
 -> 뜻이 잘 맞는 귀인을 얻어 사업이 잘 풀리며 능력 있는 직원이 많은 이익을 가져다 준다.

죽여야 할 돼지나 싸워야 할 돼지가 갑자기 사람이 되는 꿈 해몽
 -> 경쟁상대가 우세해지거나 동정, 실의 등으로 매사에 좌절하게 된다.

죽은 돼지를 짊어지고 오거나 보는 꿈 해몽
 -> 집안에 근심 걱정이 생기며, 사업은 부진해질 징조이다.

집 밖으로 돼지가 달아나는 꿈 해몽
 -> 손재수가 발생하여 손실을 보거나 가업의 부진해지는 등 장애가 생긴다.

로 돼지고기를 썰거나 돼지고기를 먹는 꿈 해몽
 -> 질병이나 금전상의 손실 등 좋지 않은 일이 발생할 징후다.

칼이나 창을 던져서 멧돼지를 죽이는 꿈 해몽
 -> 자신을 너무 억제하기에 오히려 자신의 앞길을 막고 있다고 알려 주는 꿈이다.

털이 하얀 돼지를 보는 꿈 해몽
 -> 직장에서 발전과 영예가 따르는 길몽이다.

홍수에 떠밀려 온 죽은 돼지를 건져서 집으로 가지고 오는 꿈 해몽
 -> 가정에 화근이 생길 것이다.

황소 만한 돼지가 가는 곳마다 따라오는 꿈 해몽
 -> 재산이 많은 사람의 도움을 받아 경제적으로는 풍족하지만 심적 부담을 느끼게 된다.돼지가 옆에서 따라오면 하는 일마다 실패가 없으며 남이 부러워할 정도로 순탄한 길을 걷게 된다.


- copy coding -


Google Maps Platform 사이트에 가면 구글에서 제공하는 현재 위치 표시 소스가 있습니다.

이걸 이용해서 핸드폰에 현재 위치를 표시해 보도록 하겠습니다.

 

순서

1. 프로젝트 생성

2. Source Code 작성

2.1 AndroidManifest.xml

2.2 activity_main.xml

2.3 custom_info_contents.xml

2.4 current_place_menu.xml

2.5 strings.xml

2.6 build.gradle (Project)

2.7 build.gradle (Module)

2.8 MainActivity.java

3. 결과

4. APK

5. 전체 Source Code

5.1 AndroidManifest.xml

5.2 activity_main.xml

5.3 custom_info_contents.xml

5.4 current_place_menu.xml

5.5 strings.xml

5.6 build.gradle (Project)

5.7 build.gradle (Module)

5.8 MainActivity.java

 

 

사이트 주소

https://developers.google.com/maps/documentation/android-sdk/current-place-tutorial

에 접속하면 Source code와 함께 자세한 설명이 나와있습니다.



< > Show/Hide the Java code for the map activity.

이글을 클릭하면 소스 전체 보기가 펼쳐 집니다.

이 소스를 이용하여 프로젝트를 생성해 보겠습니다.


최종 결과는 현재 위치 표시와 근처 가계 정보가 나옵니다.


구글맵 현재 위치 표시


 

 

1. 프로젝트 생성

 

제목을 제외하고는 모두 기본 설정을 사용 했습니다.





package명을 이용하여



Google map API키에 등록 합니다.



API Key 생성과 등록에 대한 설명이 필요하면



[안드로이드] google map 사용을 위한 API 키 생성(2018.11)


[안드로이드] google map 테스트


기존 설명을 참고 하세요.



2. Source Code 작성


google 에서 제공하는 위치 정보에는 현재 위치에 대한 지역정보를 보여주도록 되어있어서 불필요한 설정들이 있습니다.

, 지역정보가 필요 없다면 생략해도 되는 소스들이 많이 있어 Resource 설정부분이 좀 복잡합니다.

일단은 모두 기록를 하였으니 필요없는 부분은 생략해서 사용하세요.

 

2.1 AndroidManifest.xml


권한 설정을 추가 합니다.

 

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission
android:name="android.permission.INTERNET"/>

 

API 키도 추가해 줍니다.

 

<meta-data
   
android:name="com.google.android.geo.API_KEY"
   
android:value="Axxxxxxxxxxxxxxxxxxxxxxxxxxxx_x1" />

 

<meta-data
   
android:name="com.google.android.gms.version"
   
android:value="@integer/google_play_services_version" />

 

 

2.2 activity_main.xml

 

layoutfragment를 추가 합니다.

 

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
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="com.example.currentplacedetailsonmap.MapsActivityCurrentPlace" />

 

2.3 custom_info_contents.xml


res>layout에 현재 위치의 지역정보를 보여주는 레이아웃 정보를 추가 합니다.

필요가 없다면 생략해도 됩니다.

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
   
android:layout_width="wrap_content"
   
android:layout_height="wrap_content"
   
android:layoutDirection="locale"
   
android:orientation="vertical">
    <TextView
       
android:id="@+id/title"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:layout_gravity="center_horizontal"
       
android:textColor="#ff000000"
       
android:textStyle="bold" />

    <TextView
       
android:id="@+id/snippet"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:textColor="#ff7f7f7f" />
</LinearLayout>

 

2.4 current_place_menu.xml


res>menu에 추가 합니다.

현재 위치의 지역정보를 보여주기 위한 메뉴입니다.

필요 없다면 생략 합니다.

 

<?xml version="1.0" encoding="utf-8"?><!--
     Copyright (C) 2016 The Android Open Source Project
     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->
<menu xmlns:android="http://schemas.android.com/apk/res/android"
   
xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
       
android:id="@+id/option_get_place"
       
android:title="@string/option_get_place"
       
app:showAsAction="always"/>
</menu>

 

2.5 strings.xml


메뉴등 텍스트 정보를 추가 합니다.

그냥 layout에 하드코딩 해도 됩니다.

<resources>
    <string
name="app_name">MyLocation</string>
    <string
name="default_info_title">Default Location</string>
    <string
name="default_info_snippet">No places found, because location permission is disabled.</string>
    <string
name="option_get_place">Get place</string>
    <string
name="pick_place">Choose a place</string>
</resources>

 

2.6 build.gradle (Project)


gms 추가

classpath 'com.google.gms:google-services:3.1.0'

 

2.7 build.gradle (Module)


gms 추가

 

implementation 'com.android.support:support-v4:27.1.1'
implementation 'com.google.android.gms:play-services-maps:15.0.0'
implementation 'com.google.android.gms:play-services-location:15.0.0'
implementation 'com.google.android.gms:play-services-places:15.0.0'

 

 

2.8 MainActivity.java


google 사이트 소스를 복사 합니다.

 

작성된 코드는 원본과 세곳이 다릅니다.

 

class 명이 기본 값이라 TAG 생성시 MainActivity를 사용했습니다.

private static final String TAG = MainActivity.class.getSimpleName();

기본 좌표를 한국으로 변경했습니다.

private final LatLng mDefaultLocation = new LatLng(37.56, 126.97);

layout도 기본설정이라 activity_main으로 사용합니다.

setContentView(R.layout.activity_main);

 

 

3. 결과


주말에 돌아다니다 캡처를 해봤습니다.

우측 상단 GET PLACE를 클릭하면 주변 정보를 보여줍니다.



 

4. APK

 

소스코드 작업이 귀찮을때는 다운받아 테스트 해보세요.


MyLocation.apk




5. 전체 Source Code


android mylocation

 

5.1 AndroidManifest.xml


 

<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
   
package="copycoding.tistory.mylocation">

    <uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission
android:name="android.permission.INTERNET"/>

    <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">

        <meta-data
           
android:name="com.google.android.gms.version"
           
android:value="@integer/google_play_services_version" />

        <meta-data
           
android:name="com.google.android.geo.API_KEY"
           
android:value="Xxxxxxxxxxxxxxxxxxxxxxxxxxxx_x1" />

        <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>

 

5.2 activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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"
   
tools:context=".MainActivity">

    <fragment
xmlns:android="http://schemas.android.com/apk/res/android"
       
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="com.example.currentplacedetailsonmap.MapsActivityCurrentPlace" />

</android.support.constraint.ConstraintLayout>

 

5.3 custom_info_contents.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
   
android:layout_width="wrap_content"
   
android:layout_height="wrap_content"
   
android:layoutDirection="locale"
   
android:orientation="vertical">
    <TextView
       
android:id="@+id/title"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:layout_gravity="center_horizontal"
       
android:textColor="#ff000000"
       
android:textStyle="bold" />

    <TextView
       
android:id="@+id/snippet"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:textColor="#ff7f7f7f" />
</LinearLayout>

 

5.4 current_place_menu.xml


<?xml version="1.0" encoding="utf-8"?><!--
     Copyright (C) 2016 The Android Open Source Project
     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->
<menu xmlns:android="http://schemas.android.com/apk/res/android"
   
xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
       
android:id="@+id/option_get_place"
       
android:title="@string/option_get_place"
       
app:showAsAction="always"/>
</menu>

 

5.5 strings.xml


<resources>
    <string
name="app_name">MyLocation</string>
    <string
name="default_info_title">Default Location</string>
    <string
name="default_info_snippet">No places found, because location permission is disabled.</string>
    <string
name="option_get_place">Get place</string>
    <string
name="pick_place">Choose a place</string>
</resources>

 

5.6 build.gradle (Project)


// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
   
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath
'com.android.tools.build:gradle:3.2.1'

       
classpath 'com.google.gms:google-services:3.1.0'
       

       
// NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
   
}
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(
type: Delete) {
    delete
rootProject.buildDir
}

 

5.7 build.gradle (Module)


apply plugin: 'com.android.application'

android {
    compileSdkVersion
28
   
defaultConfig {
       
applicationId "copycoding.tistory.mylocation"
       
minSdkVersion 14
       
targetSdkVersion 28
       
versionCode 1
       
versionName "1.0"
       
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
   
}
    buildTypes {
        release {
           
minifyEnabled false
           
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
       
}
    }
}

dependencies {
    implementation fileTree(
dir: 'libs', include: ['*.jar'])
    implementation
'com.android.support:appcompat-v7:28.0.0'
   
implementation 'com.android.support:support-v4:27.1.1'
   
implementation 'com.google.android.gms:play-services-maps:15.0.0'
   
implementation 'com.google.android.gms:play-services-location:15.0.0'
   
implementation 'com.google.android.gms:play-services-places:15.0.0'
   
   
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
   
testImplementation 'junit:junit:4.12'
   
androidTestImplementation 'com.android.support.test:runner:1.0.2'
   
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

 

5.8 MainActivity.java

 

package copycoding.tistory.mylocation;

import
android.content.DialogInterface;
import
android.content.pm.PackageManager;
import
android.location.Location;
import
android.os.Bundle;
import
android.support.annotation.NonNull;
import
android.support.v4.app.ActivityCompat;
import
android.support.v4.content.ContextCompat;
import
android.support.v7.app.AlertDialog;
import
android.support.v7.app.AppCompatActivity;
import
android.util.Log;
import
android.view.Menu;
import
android.view.MenuItem;
import
android.view.View;
import
android.widget.FrameLayout;
import
android.widget.TextView;

import
com.google.android.gms.location.FusedLocationProviderClient;
import
com.google.android.gms.location.LocationServices;
import
com.google.android.gms.location.places.GeoDataClient;
import
com.google.android.gms.location.places.PlaceDetectionClient;
import
com.google.android.gms.location.places.PlaceLikelihood;
import
com.google.android.gms.location.places.PlaceLikelihoodBufferResponse;
import
com.google.android.gms.location.places.Places;
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.CameraPosition;
import
com.google.android.gms.maps.model.LatLng;
import
com.google.android.gms.maps.model.Marker;
import
com.google.android.gms.maps.model.MarkerOptions;
import
com.google.android.gms.tasks.OnCompleteListener;
import
com.google.android.gms.tasks.Task;

import
java.util.Locale;

public class
MainActivity extends AppCompatActivity implements OnMapReadyCallback {

   
private static final String TAG = MainActivity.class.getSimpleName();
    private
GoogleMap mMap;
    private
CameraPosition mCameraPosition;

   
// The entry points to the Places API.
   
private GeoDataClient mGeoDataClient;
    private
PlaceDetectionClient mPlaceDetectionClient;

   
// The entry point to the Fused Location Provider.
   
private FusedLocationProviderClient mFusedLocationProviderClient;
   
// A default location (Sydney, Australia) and default zoom to use when location permission is
    // not granted.
   
private final LatLng mDefaultLocation = new LatLng(37.56, 126.97);
    private static final int
DEFAULT_ZOOM = 15;
    private static final int
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
    private boolean
mLocationPermissionGranted;

    private
Location mLastKnownLocation;

   
// Keys for storing activity state.
   
private static final String KEY_CAMERA_POSITION = "camera_position";
    private static final
String KEY_LOCATION = "location";

   
// Used for selecting the current place.
   
private static final int M_MAX_ENTRIES = 5;
    private
String[] mLikelyPlaceNames;
    private
String[] mLikelyPlaceAddresses;
    private
String[] mLikelyPlaceAttributions;
    private
LatLng[] mLikelyPlaceLatLngs;

   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
       
// Retrieve location and camera position from saved instance state.
       
if (savedInstanceState != null) {
           
mLastKnownLocation = savedInstanceState.getParcelable(KEY_LOCATION);
           
mCameraPosition = savedInstanceState.getParcelable(KEY_CAMERA_POSITION);
       
}
        setContentView(R.layout.
activity_main);

       
mGeoDataClient = Places.getGeoDataClient(this, null);
       
mPlaceDetectionClient = Places.getPlaceDetectionClient(this, null);
       
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

       

        // Build the map.
       
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.
map);
       
mapFragment.getMapAsync(this);
   
}

   
/**
     * Saves the state of the map when the activity is paused.
     */
   
@Override
   
protected void onSaveInstanceState(Bundle outState) {
       
if (mMap != null) {
            outState.putParcelable(
KEY_CAMERA_POSITION, mMap.getCameraPosition());
            
outState.putParcelable(KEY_LOCATION, mLastKnownLocation);
            super
.onSaveInstanceState(outState);
       
}
    }

   
/**
     * Sets up the options menu.
     * @param
menu The options menu.
     * @return Boolean.
     */
   
@Override
   
public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.
current_place_menu, menu);
        return true;
   
}

   
/**
     * Handles a click on the menu option to get a place.
     * @param
item The menu item to handle.
     * @return Boolean.
     */
   
@Override
   
public boolean onOptionsItemSelected(MenuItem item) {
       
if (item.getItemId() == R.id.option_get_place) {
            showCurrentPlace()
;
       
}
       
return true;
   
}

   
/**
     * Manipulates the map when it's available.
     * This callback is triggered when the map is ready to be used.
     */
   
@Override
   
public void onMapReady(GoogleMap map) {
       
mMap = map;

       
// Use a custom info window adapter to handle multiple lines of text in the
        // info window contents.
       
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {

           
@Override
           
// Return null here, so that getInfoContents() is called next.
           
public View getInfoWindow(Marker arg0) {
               
return null;
           
}

           
@Override
           
public View getInfoContents(Marker marker) {
               
// Inflate the layouts for the info window, title and snippet.
               
View infoWindow = getLayoutInflater().inflate(R.layout.custom_info_contents,
                       
(FrameLayout) findViewById(R.id.map), false);

               
TextView title = ((TextView) infoWindow.findViewById(R.id.title));
               
title.setText(marker.getTitle());

               
TextView snippet = ((TextView) infoWindow.findViewById(R.id.snippet));
               
snippet.setText(marker.getSnippet());

                return
infoWindow;
           
}
        })
;

       
// Prompt the user for permission.
        
getLocationPermission();

       
// Turn on the My Location layer and the related control on the map.
       
updateLocationUI();

       
// Get the current location of the device and set the position of the map.
       
getDeviceLocation();
   
}

    
/**
     * Gets the current location of the device, and positions the map's camera.
     */
   
private void getDeviceLocation() {
       
/*
         * Get the best and most recent location of the device, which may be null in rare
         * cases when a location is not available.
         */
       
try {
           
if (mLocationPermissionGranted) {
                Task<Location> locationResult =
mFusedLocationProviderClient.getLastLocation();
               
locationResult.addOnCompleteListener(this, new OnCompleteListener<Location>() {
                   
@Override
                   
public void onComplete(@NonNull Task<Location> task) {
                       
if (task.isSuccessful()) {
                           
// Set the map's camera position to the current location of the device.
                           
mLastKnownLocation = task.getResult();
                           
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
                                   
new LatLng(mLastKnownLocation.getLatitude(),
                                           
mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
                       
} else {
                            Log.d(
TAG, "Current location is null. Using defaults.");
                           
Log.e(TAG, "Exception: %s", task.getException());
                           
mMap.moveCamera(CameraUpdateFactory
                                    .newLatLngZoom(
mDefaultLocation, DEFAULT_ZOOM));
                           
mMap.getUiSettings().setMyLocationButtonEnabled(false);
                       
}
                    }
                })
;
           
}
        }
catch (SecurityException e)  {
            Log.e(
"Exception: %s", e.getMessage());
       
}
    }


   
/**
     * Prompts the user for permission to use the device location.
     */
   
private void getLocationPermission() {
       
/*
         * Request location permission, so that we can get the location of the
         * device. The result of the permission request is handled by a callback,
         * onRequestPermissionsResult.
         */
       
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
               
android.Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.
PERMISSION_GRANTED) {
           
mLocationPermissionGranted = true;
       
} else {
            ActivityCompat.requestPermissions(
this,
                    new
String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                   
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
       
}
    }

   
/**
     * Handles the result of the request for location permissions.
     */
   
@Override
   
public void onRequestPermissionsResult(int requestCode,
                                          
@NonNull String permissions[],
                                           
@NonNull int[] grantResults) {
       
mLocationPermissionGranted = false;
        switch
(requestCode) {
           
case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
               
// If request is cancelled, the result arrays are empty.
               
if (grantResults.length > 0
                       
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                   
mLocationPermissionGranted = true;
               
}
            }
        }
        updateLocationUI()
;
   
}

   
/**
     * Prompts the user to select the current place from a list of likely places, and shows the
     * current place on the map - provided the user has granted location permission.
     */
   
private void showCurrentPlace() {
       
if (mMap == null) {
           
return;
       
}

       
if (mLocationPermissionGranted) {
           
// Get the likely places - that is, the businesses and other points of interest that
            // are the best match for the device's current location.
           
@SuppressWarnings("MissingPermission") final
           
Task<PlaceLikelihoodBufferResponse> placeResult =
                   
mPlaceDetectionClient.getCurrentPlace(null);
           
placeResult.addOnCompleteListener
                    (
new OnCompleteListener<PlaceLikelihoodBufferResponse>() {
                       
@Override
                       
public void onComplete(@NonNull Task<PlaceLikelihoodBufferResponse> task) {
                           
if (task.isSuccessful() && task.getResult() != null) {
                                PlaceLikelihoodBufferResponse likelyPlaces = task.getResult()
;

                               
// Set the count, handling cases where less than 5 entries are returned.
                                
int count;
                                if
(likelyPlaces.getCount() < M_MAX_ENTRIES) {
                                    count = likelyPlaces.getCount()
;
                               
} else {
                                    count =
M_MAX_ENTRIES;
                               
}

                               
int i = 0;
                               
mLikelyPlaceNames = new String[count];
                               
mLikelyPlaceAddresses = new String[count];
                                
mLikelyPlaceAttributions = new String[count];
                               
mLikelyPlaceLatLngs = new LatLng[count];

                                for
(PlaceLikelihood placeLikelihood : likelyPlaces) {
                                   
// Build a list of likely places to show the user.
                                   
mLikelyPlaceNames[i] = (String) placeLikelihood.getPlace().getName();
                                   
mLikelyPlaceAddresses[i] = (String) placeLikelihood.getPlace()
                                            .getAddress()
;
                                   
mLikelyPlaceAttributions[i] = (String) placeLikelihood.getPlace()
                                            .getAttributions()
;
                                    
mLikelyPlaceLatLngs[i] = placeLikelihood.getPlace().getLatLng();

                                   
i++;
                                    if
(i > (count - 1)) {
                                       
break;
                                   
}
                                }

                               
// Release the place likelihood buffer, to avoid memory leaks.
                               
likelyPlaces.release();

                               
// Show a dialog offering the user the list of likely places, and add a
                                // marker at the selected place.
                               
openPlacesDialog();

                           
} else {
                                Log.e(
TAG, "Exception: %s", task.getException());
                           
}
                        }
                    })
;
       
} else {
           
// The user has not granted permission.
           
Log.i(TAG, "The user did not grant location permission.");

           
// Add a default marker, because the user hasn't selected a place.
           
mMap.addMarker(new MarkerOptions()
                    .title(getString(R.string.
default_info_title))
                    .position(
mDefaultLocation)
                    .snippet(getString(R.string.
default_info_snippet)));

           
// Prompt the user for permission.
           
getLocationPermission();
       
}
    }

   
/**
     * Displays a form allowing the user to select a place from a list of likely places.
     */
   
private void openPlacesDialog() {
       
// Ask the user to choose the place where they are now.
       
DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
           
@Override
           
public void onClick(DialogInterface dialog, int which) {
               
// The "which" argument contains the position of the selected item.
               
LatLng markerLatLng = mLikelyPlaceLatLngs[which];
               
String markerSnippet = mLikelyPlaceAddresses[which];
                if
(mLikelyPlaceAttributions[which] != null) {
                    markerSnippet = markerSnippet +
"\n" + mLikelyPlaceAttributions[which];
               
}

               
// Add a marker for the selected place, with an info window
                // showing information about that place.
               
mMap.addMarker(new MarkerOptions()
                        .title(
mLikelyPlaceNames[which])
                        .position(markerLatLng)
                        .snippet(markerSnippet))
;

               
// Position the map's camera at the location of the marker.
               
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(markerLatLng,
                       
DEFAULT_ZOOM));
           
}
        }
;

       
// Display the dialog.
       
AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle(R.string.
pick_place)
                .setItems(
mLikelyPlaceNames, listener)
                .show()
;
   
}

   
/**
     * Updates the map's UI settings based on whether the user has granted location permission.
     */
   
private void updateLocationUI() {
       
if (mMap == null) {
           
return;
       
}
       
try {
           
if (mLocationPermissionGranted) {
               
mMap.setMyLocationEnabled(true);
               
mMap.getUiSettings().setMyLocationButtonEnabled(true);
           
} else {
               
mMap.setMyLocationEnabled(false);
               
mMap.getUiSettings().setMyLocationButtonEnabled(false);
               
mLastKnownLocation = null;
               
getLocationPermission();
           
}
        }
catch (SecurityException e)  {
            Log.e(
"Exception: %s", e.getMessage());
       
}
    }
}

 

- copy coding - 


1···93949596979899···118

+ Recent posts