Skip to content

Commit

Permalink
update : AndroidBridege에서 'android' 로 호출할 수 있도록 변경, 도로명 주소까지 반환하도록 변경
Browse files Browse the repository at this point in the history
  • Loading branch information
tgyuuAn committed Jul 28, 2024
1 parent c4c935a commit 3290418
Show file tree
Hide file tree
Showing 2 changed files with 174 additions and 66 deletions.
77 changes: 76 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,79 @@

<br><br><br>

**WebView**를 사용할 때 url을`tgyuuan.github.io/DaumAddressApi`로 설정하고 사용하면 된다.
**WebView**를 사용할 때 url을`https://tgyuuan.github.io/DaumAddressApi`로 설정하고 사용하면 된다.

```kotlin
@AndroidEntryPoint
class PostCodeFragment : DialogFragment() {

private var _binding: FragmentPostCodeBinding? = null
private val binding get() = _binding!!

override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentPostCodeBinding.inflate(inflater, container, false)
binding.lifecycleOwner = this.viewLifecycleOwner
return binding.root
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupWebView()
}

override fun onDestroyView() {
super.onDestroyView()
_binding = null
}

@SuppressLint("SetJavaScriptEnabled")
private fun setupWebView() {
binding.postcodeWV.apply {
settings.javaScriptEnabled = true
settings.domStorageEnabled = true
settings.useWideViewPort = true
settings.loadWithOverviewMode = true
settings.cacheMode = WebSettings.LOAD_NO_CACHE

webViewClient = WebViewClient()
webChromeClient = WebChromeClient()

addJavascriptInterface(AndroidBridge(), "android")
loadUrl("https://tgyuuan.github.io/DaumAddressApi")
}
}

private inner class AndroidBridge {
@JavascriptInterface
fun onPostCodeReceived(roadNameAddress: String, lotNumberAddress: String) {

// 여기서 받아온 데이터를 핸들링 할 코드를 작성

dismiss()
}
}
}
```

```xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">

<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".PostCodeFragment">

<WebView
android:id="@+id/postcode_WV"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp" />
</FrameLayout>
</layout>
```
163 changes: 98 additions & 65 deletions index.html
Original file line number Diff line number Diff line change
@@ -1,104 +1,132 @@
<!DOCTYPE html>
<html>
<head>
<style>
/* 레이어를 화면 전체에 꽉 차도록 설정 */
#layer {
display: block;
position: fixed;
overflow: hidden;
z-index: 1;
-webkit-overflow-scrolling: touch;
width: 100%;
height: 100%;
}
#wrap {
display: none;
border: 1px solid;
width: 500px;
height: 300px;
margin: 5px 0;
position: relative;
}
#btnFoldWrap {
cursor: pointer;
position: absolute;
right: 0px;
top: -1px;
z-index: 1;
}
</style>
</head>
<body>

<!-- iOS에서는 position:fixed 버그가 있음, 적용하는 사이트에 맞게 position:absolute 등을 이용하여 top,left값 조정 필요 -->
<div id="layer" style="display:block;position:fixed;overflow:hidden;z-index:1;-webkit-overflow-scrolling:touch;">
<input type="text" id="sample3_postcode" placeholder="우편번호">
<input type="button" onclick="sample3_execDaumPostcode()" value="우편번호 찾기"><br>
<input type="text" id="sample3_address" placeholder="주소"><br>
<input type="text" id="sample3_detailAddress" placeholder="상세주소">
<input type="text" id="sample3_extraAddress" placeholder="참고항목">

<div id="wrap">
<img src="//t1.daumcdn.net/postcode/resource/images/close.png" id="btnFoldWrap" onclick="foldDaumPostcode()" alt="접기 버튼">
</div>

<script src="http://dmaps.daum.net/map_js_init/postcode.v2.js"></script>
<script>


window.addEventListener("message", onReceivedPostMessage, false);
<div id="layer"></div>

function onReceivedPostMessage(event){
//..ex deconstruct event into action & params
var action = event.data.action;
var params = event.data.params;

console.log("onReceivedPostMessage "+event);

}
<script src="https://t1.daumcdn.net/mapjsapi/bundle/postcode/prod/postcode.v2.js"></script>
<script>
var element_layer = document.getElementById('layer');
var element_wrap = document.getElementById('wrap');

function onReceivedActivityMessageViaJavascriptInterface(json){
//..ex deconstruct data into action & params
var data = JSON.parse(json);
var action = data.action;
var params = data.params;
console.log("onReceivedActivityMessageViaJavascriptInterface "+event);
function foldDaumPostcode() {
// iframe을 넣은 element를 안보이게 한다.
element_wrap.style.display = 'none';
element_layer.style.display = 'none';
}


// 우편번호 찾기 화면을 넣을 element
var element_layer = document.getElementById('layer');

function sample2_execDaumPostcode() {
function sample3_execDaumPostcode() {
// 현재 scroll 위치를 저장해놓는다.
var currentScroll = Math.max(document.body.scrollTop, document.documentElement.scrollTop);
new daum.Postcode({
oncomplete: function(data) {

// 검색결과 항목을 클릭했을때 실행할 코드를 작성하는 부분.

// 각 주소의 노출 규칙에 따라 주소를 조합한다.
// 내려오는 변수가 값이 없는 경우엔 공백('')값을 가지므로, 이를 참고하여 분기 한다.
var fullAddr = data.address; // 최종 주소 변수
var extraAddr = ''; // 조합형 주소 변수
var addr = ''; // 주소 변수
var extraAddr = ''; // 참고항목 변수

//사용자가 선택한 주소 타입에 따라 해당 주소 값을 가져온다.
if (data.userSelectedType === 'R') { // 사용자가 도로명 주소를 선택했을 경우
addr = data.roadAddress;
} else { // 사용자가 지번 주소를 선택했을 경우(J)
addr = data.jibunAddress;
}

// 기본 주소가 도로명 타입일때 조합한다.
if(data.addressType === 'R'){
//법정동명이 있을 경우 추가한다.
if(data.bname !== ''){
// 사용자가 선택한 주소가 도로명 타입일때 참고항목을 조합한다.
if(data.userSelectedType === 'R'){
// 법정동명이 있을 경우 추가한다. (법정리는 제외)
// 법정동의 경우 마지막 문자가 "동/로/가"로 끝난다.
if(data.bname !== '' && /[동|로|가]$/g.test(data.bname)){
extraAddr += data.bname;
}
// 건물명이 있을 경우 추가한다.
if(data.buildingName !== ''){
// 건물명이 있고, 공동주택일 경우 추가한다.
if(data.buildingName !== '' && data.apartment === 'Y'){
extraAddr += (extraAddr !== '' ? ', ' + data.buildingName : data.buildingName);
}
// 조합형주소의 유무에 따라 양쪽에 괄호를 추가하여 최종 주소를 만든다.
fullAddr += (extraAddr !== '' ? ' ('+ extraAddr +')' : '');
// 표시할 참고항목이 있을 경우, 괄호까지 추가한 최종 문자열을 만든다.
if(extraAddr !== ''){
extraAddr = ' (' + extraAddr + ')';
}
// 조합된 참고항목을 해당 필드에 넣는다.
document.getElementById("sample3_extraAddress").value = extraAddr;

} else {
document.getElementById("sample3_extraAddress").value = '';
}

// 우편번호와 주소 정보를 해당 필드에 넣는다.
document.getElementById('sample3_postcode').value = data.zonecode;
document.getElementById("sample3_address").value = addr;
// 커서를 상세주소 필드로 이동한다.
document.getElementById("sample3_detailAddress").focus();

var fullRoadAddr = data.roadAddress; // 도로명 주소 변수
var extraRoadAddr = ''; // 도로명 조합형 주소 변수
// 도로명 주소와 지번 주소를 안드로이드 네이티브로 전송
var roadNameAddress = addr + extraAddr;
var lotNumberAddress = data.jibunAddress;
window.android.onPostCodeReceived(roadNameAddress, lotNumberAddress);

// 법정동명이 있을 경우 추가한다. (법정리는 제외)
// 법정동의 경우 마지막 문자가 "동/로/가"로 끝난다.
if(data.bname !== '' && /[동|로|가]$/g.test(data.bname)){
extraRoadAddr += data.bname;
}
// 건물명이 있고, 공동주택일 경우 추가한다.
if(data.buildingName !== '' && data.apartment === 'Y'){
extraRoadAddr += (extraRoadAddr !== '' ? ', ' + data.buildingName : data.buildingName);
}
// 도로명, 지번 조합형 주소가 있을 경우, 괄호까지 추가한 최종 문자열을 만든다.
if(extraRoadAddr !== ''){
extraRoadAddr = ' (' + extraRoadAddr + ')';
}
// 도로명, 지번 주소의 유무에 따라 해당 조합형 주소를 추가한다.
if(fullRoadAddr !== ''){
fullRoadAddr += extraRoadAddr;
}
// iframe을 넣은 element를 안보이게 한다.
element_wrap.style.display = 'none';
element_layer.style.display = 'none';

// 주소만 필요하므로 이것만 전송한다.
window.MysosoApp.processDATA(fullRoadAddr);
// 우편번호 찾기 화면이 보이기 이전으로 scroll 위치를 되돌린다.
document.body.scrollTop = currentScroll;
},
// 우편번호 찾기 화면 크기가 조정되었을때 실행할 코드를 작성하는 부분. iframe을 넣은 element의 높이값을 조정한다.
onresize : function(size) {
element_wrap.style.height = size.height+'px';
},
width : '100%',
height : '100%'
}).embed(element_layer);
}).embed(element_wrap);

// iframe을 넣은 element를 보이게 한다.
element_wrap.style.display = 'block';
element_layer.style.display = 'block';

// iframe을 넣은 element의 위치를 화면의 가운데로 이동시킨다.
initLayerPosition();
}
// 브라우저의 크기 변경에 따라 레이어를 가운데로 이동시키고자 하실때에는
// resize이벤트나, orientationchange이벤트를 이용하여 값이 변경될때마다 아래 함수를 실행 시켜 주시거나,
// 직접 element_layer의 top,left값을 수정해 주시면 됩니다.

function initLayerPosition(){
var width = (window.innerWidth || document.documentElement.clientWidth); //우편번호서비스가 들어갈 element의 width
var height = (window.innerHeight || document.documentElement.clientHeight); //우편번호서비스가 들어갈 element의 height
Expand All @@ -112,6 +140,11 @@
element_layer.style.left = (((window.innerWidth || document.documentElement.clientWidth) - width)/2 - borderWidth) + 'px';
element_layer.style.top = (((window.innerHeight || document.documentElement.clientHeight) - height)/2 - borderWidth) + 'px';
}

// Daum Postcode API를 초기화하고 실행
window.onload = function() {
sample3_execDaumPostcode();
};
</script>
</body>
</html>
</html>

0 comments on commit 3290418

Please sign in to comment.