window.kmodule = window.kmodule || {} kmodule.gps = (function () { var success = "/img/pin_success.png" fail = "/img/pin_fail.png", geocoder = new kakao.maps.services.Geocoder(), xhr = new XMLHttpRequest(), imageSize = new kakao.maps.Size(24, 24), markersuccess = new kakao.maps.MarkerImage(success, imageSize), markerfail = new kakao.maps.MarkerImage(fail, imageSize), distance_standard = 1000, // 반경 기본값 gps_list = "", //gps 데이터 리스트 mapOption = "", //지도 옵션 mapContainer = "", // 지도를 표시할 div defaultcenter = new kakao.maps.LatLng(37.4999925, 127.0287775), // 강남이 첫 센터 map = "", // 지도를 생성합니다 circle = "", // 반경 marker_arr = [], //마커 담고 있는 배열 => 초기화 용 info_arr = [], polygon = {}, // 폴리곤 값 areaCode = "", // 지역구 코드 count = { "error": 0, "success": 0, "none": 0 } /** * * @date 2020-12-03 * @param {*} id * 받은 id에 지도 표시 */ function make_map(id) { mapOption = { center: defaultcenter, // 지도의 중심좌표 level: 8 // 지도의 확대 레벨 }; mapContainer = document.getElementById(id); // 지도를 표시할 div kmodule.gps.map = new kakao.maps.Map(mapContainer, mapOption); // 지도를 생성합니다 } /** * * @date 2020-12-03 * @param {*} lat 위도 * @param {*} lng 경도 * @param {*} type 마커 타입 * @param {*} fnc 마커에 걸 이벤트 함수 */ function make_marker(lat, lng, type, infoText,fnc) { var xy = new kakao.maps.LatLng(lat, lng); type = type || "fail" var img = type if (img === "fail") img = markerfail else if (img === "success") img = markersuccess var marker = new kakao.maps.Marker({ map: kmodule.gps.map, position: xy, clickable: true, image: img // 마커이미지 설정 }); marker_arr.push(marker) marker.setPosition(xy); marker.setMap(kmodule.gps.map); if(infoText) { var thisContent = "
"+(infoText||"")+"
" var infoWindow = new kakao.maps.InfoWindow({ position: xy, content: thisContent, removable: true }); info_arr.push(infoWindow) infoWindow.open(kmodule.gps.map, marker) } if (type === "fail") { kakao.maps.event.addListener(marker, "click", fnc); } } /** * * @date 2020-12-03 * @param {*} node * 지도 위에 넘어온 node를 좌측 상단에 띄운다 */ function infobox_on_map(node) { var offset = $(mapContainer).offset(); var top = (offset.top + 10) + "px"; var left = (offset.left + 10) + "px"; $("#Info_box").remove(); setAttributes(node, { "id": "Info_box", "style": "z-index:50;position:absolute;top:" + top + ";left:" + left }); $("body").append(node); } /** * @date 2020-12-03 * 마커 지우기 */ function remove_marker() { marker_arr.forEach(function (m) { m.setMap(null) }); info_arr.forEach(function (m) { m.setMap(null) }) } /** * * @date 2020-12-03 * @param {*} el => 주소값을 담은 object * @returns * 두 위치의 차이를 구하면서 검증 시작 */ function get_distance(el) { return new Promise(function (resolve, reject) { geocoder.addressSearch(el.address, function (result, status) { // 정상적으로 검색이 완료됐으면 if (status === kakao.maps.services.Status.OK) { var latlng = [el.lat, el.lon]; var get_distance = +distance(result[0].y, result[0].x, latlng[0], latlng[1], "meter") if (get_distance > distance_standard) { count.error++ el.gps_flag = "2"; } else { count.success++ el.gps_flag = "1"; } } else { count.none++; el.gps_flag = "9"; } resolve("OK"); }); }) } /** * * @date 2020-12-03 * @param {*} list => 업데이트 할 GPS * GPS 리스트 업데이트 */ function setlist(list) { gps_list = list } /** * * @date 2020-12-03 * @param {*} area => 주소 [000도00시00동] * 동을 넘길 경우 해당 지역구 코드를 getPolygon에 넘겨줌 */ function printPolygon(area) { xhr.open("GET", encodeURI("https://dapi.kakao.com/v2/local/search/address.json?query="+area), true); xhr.setRequestHeader("Authorization", "KakaoAK a18e1051dc534d8de05cbac72a49d8ec"); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { var areaJson = JSON.parse(xhr.responseText) var x = areaJson.documents[0].address.x var y = areaJson.documents[0].address.y kmodule.gps.areaCode = areaJson.documents[0].address.b_code getPolygon(left(kmodule.gps.areaCode, 5), 2); getPolygon(left(kmodule.gps.areaCode, kmodule.gps.areaCode.length - 2), 1); kmodule.gps.map.setCenter(new kakao.maps.LatLng(y, x)); } } xhr.send(); } /** * * @date 2020-12-03 * @param {*} value => 지역 코드 * @param {*} type => 읍면동, 시군구 구별 * 지도의 폴리곤 값 가져오기 vworld API 사용 */ function getPolygon(value, type) { var outline_type, polygon_type /* type === 1 => 읍면동, type === 2 => 시군구 */ type === 1 ? outline_type = "LT_C_ADEMD_INFO" : outline_type = "LT_C_ADSIGG_INFO" var data = "key=EC6922C9-5E2E-35BC-AA47-EEEEB095C4F2" data += "&domain=" + kmodule.gps.domain data += "&service=data&version=2.0&request=getfeature" data += "&format=json&size=100&page=1" data += "&data=" + outline_type + "&geometry=true&attribute=true&crs=EPSG:4326" polygon_type = { strokeWeight: 3, // 선의 두께입니다 strokeOpacity: 0.8, // 선의 불투명도 입니다 1에서 0 사이의 값이며 0에 가까울수록 투명합니다 strokeStyle: 'solid', // 선의 스타일입니다 } /* 에러 위치 */ if (type === 1) { data += "&attrfilter=emd_cd:=:" + value polygon_type.fillColor = '#fa2844' polygon_type.strokeColor = '#fa2844' polygon_type.fillOpacity = 0.5 } else { data += "&attrfilter=sig_cd:=:" + value polygon_type.fillColor = '#28ACFA' polygon_type.strokeColor = '#28ACFA' polygon_type.fillOpacity = 0.2 } $.ajax({ type: "get", url: "http://api.vworld.kr/req/data", data: data, dataType: 'jsonp', async: false, success: function (data) { var idx = 0 if (data.response.status === "OK") { data.response.result.featureCollection.features.forEach(function (geo) { polygonPath = []; geo.geometry.coordinates.forEach(function (va) { va.forEach(function (va2) { if (va2.length > 100) { va2.forEach(function (va3) { polygonPath.push(new kakao.maps.LatLng(va3[1], va3[0])); }) if (polygon[value] === undefined) polygon[value] = [] if (polygon[value][idx] !== undefined) polygon[value][idx].setMap(null); polygon_type.path = polygonPath polygon[value][idx] = new kakao.maps.Polygon(polygon_type); polygon[value][idx].setMap(kmodule.gps.map); idx++ } }); }) }); } else { alert("데이터를 가지고 올 수 없습니다."); return false; } }, error: function (xhr, stat, err) { console.log(xhr) console.log(stat) console.log(err) } }); } /** * * @date 2020-12-03 * @param {*} position -> 위치 * @param {*} dv -> 반지름 * 반경으로 검증할 때 지도에 원 표시 */ function createcircle(position, dv) { if (position) var coords = new kakao.maps.LatLng(position.y, position.x); if (circle) { circle.setMap(null) } circle = new kakao.maps.Circle({ center: coords || defaultcenter, // 원의 중심좌표 입니다 radius: dv || distance_standard, // 미터 단위의 원의 반지름입니다 strokeWeight: 3, // 선의 두께입니다 strokeColor: '#75B8FA', // 선의 색깔입니다 strokeOpacity: 1, // 선의 불투명도 입니다 1에서 0 사이의 값이며 0에 가까울수록 투명합니다 strokeStyle: 'solid', // 선의 스타일 입니다 fillColor: '#CFE7FF', // 채우기 색깔입니다 fillOpacity: 0.2 // 채우기 불투명도 입니다 }); circle.setMap(map); kmodule.gps.map.setCenter(coords || defaultcenter) } /** * * @date 2020-12-03 * @param {*} target => 누른 버튼 * GPS 검증 */ function fn_gps_verify(target) { gps_list.reduce(function (promise, el, id) { return promise.then(function () { return get_distance(el); }); }, Promise.resolve()).then(function () { alert(" 에러 개수 : " + count.error + " / 검증 실패 개수 : " + count.none) var a = array_filter_to_group(gps_list, "gps_flag"); Object.keys(a).forEach(function (key) { codelist = a[key].map(function (element) { return "'" + element.idkey + "'"; }) a[key] = codelist.join(",") }) Object.keys(a).reduce(function (promise, el, id) { var param = setparam("u", "UPDATEGPS", { "STAT": el, "list": a[el] }) return promise.then(function () { ajax_call("./include/ajax_get.asp", param); }); }, Promise.resolve()); $(target).find(".spinner-grow").remove(); $(target).attr("data-loading", "false"); }) } /** * * @date 2020-12-03 * @param {*} list gps 리스트 * 좌표값 기반으로 지역구 코드를 리스트에 추가함 */ function add_location_info(list) { var marking_code = function(ele) { return new Promise(function(resolve, reject){ kmodule.gps.geocoder.coord2RegionCode(ele.lon, ele.lat, function (result, status) { if (status === kakao.maps.services.Status.OK) { ele["code"] = result[0].code; resolve() } }) }) } return forEachPromise(list, marking_code) } function verify_to_code(list, len){ var maincode = kmodule.gps.areaCode; len = len || 5; var subcode = left(maincode, len) list.forEach(function(ele){ if(subcode !== left(ele.code,len) || maincode === ele.code) { ele.errorStat = "1" } else { ele.errorStat = "0" } }) } const module = { setlist: setlist, fn_gps_verify: fn_gps_verify, make_map: make_map, createcircle: createcircle, make_marker: make_marker, remove_marker: remove_marker, infobox_on_map: infobox_on_map, printPolygon:printPolygon, getPolygon:getPolygon, add_location_info:add_location_info, verify_to_code:verify_to_code, /* variable */ areaCode,areaCode, geocoder:geocoder, gps_list:gps_list, info_arr:info_arr } return module })();