회원가입 - 브이월드 오픈 API 中 2D 데이터API 사용

유동현·2023년 1월 30일
0

파이널프로젝트

목록 보기
1/4
post-thumbnail

발급받은 인증키 활용방법

페이지
https://www.vworld.kr/dev/v4dv_2ddataguide2_s002.do?svcIde=adsigg

참조해야할 페이지 : https://velog.io/@chaeri93/Django-%EA%B3%B5%EA%B3%B5API-%EC%A7%80%EB%8F%84%EC%97%90-%EB%A7%B5%ED%95%91%ED%95%98%EA%B8%B0

1 요청 URL

1.http://api.vworld.kr/req/data?service=data&request=GetFeature&data=LT_C_ADSIGG_INFO&key=인증키&domain=인증키 URL&[요청파라미터]

  • 이때 인증키 URL 즉 내가 서비스하겠다 신청한 URL이 없으면 작동하지 않음

2 URL 사용법

https://api.vworld.kr/req/data?service=data&request=GetFeature&data=LT_C_ADSIGG_INFO&key=발급받은 인증키&domain=인증키 URL &format=json&attrFilter=full_nm:like:서울&geometry=false

이렇게 하면 지역구 이름에 서울이 들어가는 모든 지역구가

{"response" : {"service" : {"name" : "data", "version" : "2.0", "operation" : "GetFeature", "time" : "23(ms)"}, "status" : "OK", "record" : {"total" : "25", "current" : "10"}, "page" : {"total" : "3", "current" : "1", "size" : "10"}, "result" : {"featureCollection" : {"type":"FeatureCollection","bbox":[0.0,0.0,-1.0,-1.0],"features":
[
  {"type":"Feature","properties":{"sig_cd":"11110","sig_eng_nm":"Jongno-gu","full_nm":"서울특별시 종로구","sig_kor_nm":"종로구"},"id":"LT_C_ADSIGG_INFO.5751"},

  {"type":"Feature","properties":{"sig_cd":"11140","sig_eng_nm":"Jung-gu","full_nm":"서울특별시 중구","sig_kor_nm":"중구"},"id":"LT_C_ADSIGG_INFO.5752"},
  {"type":"Feature","properties":{"sig_cd":"11170","sig_eng_nm":"Yongsan-gu","full_nm":"서울특별시 용산구","sig_kor_nm":"용산구"},"id":"LT_C_ADSIGG_INFO.5753"},
  {"type":"Feature","properties":{"sig_cd":"11200","sig_eng_nm":"Seongdong-gu","full_nm":"서울특별시 성동구","sig_kor_nm":"성동구"},"id":"LT_C_ADSIGG_INFO.5754"},
  {"type":"Feature","properties":{"sig_cd":"11215","sig_eng_nm":"Gwangjin-gu","full_nm":"서울특별시 광진구","sig_kor_nm":"광진구"},"id":"LT_C_ADSIGG_INFO.5755"},
  {"type":"Feature","properties":{"sig_cd":"11230","sig_eng_nm":"Dongdaemun-gu","full_nm":"서울특별시 동대문구","sig_kor_nm":"동대문구"},"id":"LT_C_ADSIGG_INFO.5756"},
  {"type":"Feature","properties":{"sig_cd":"11260","sig_eng_nm":"Jungnang-gu","full_nm":"서울특별시 중랑구","sig_kor_nm":"중랑구"},"id":"LT_C_ADSIGG_INFO.5757"},
  {"type":"Feature","properties":{"sig_cd":"11290","sig_eng_nm":"Seongbuk-gu","full_nm":"서울특별시 성북구","sig_kor_nm":"성북구"},"id":"LT_C_ADSIGG_INFO.5758"},
  {"type":"Feature","properties":{"sig_cd":"11305","sig_eng_nm":"Gangbuk-gu","full_nm":"서울특별시 강북구","sig_kor_nm":"강북구"},"id":"LT_C_ADSIGG_INFO.5759"},
  {"type":"Feature","properties":{"sig_cd":"11320","sig_eng_nm":"Dobong-gu","full_nm":"서울특별시 도봉구","sig_kor_nm":"도봉구"},"id":"LT_C_ADSIGG_INFO.5760"}]}
}}}

와 같이 나오게 된다.

반환데이터 결정

https://api.vworld.kr/req/data?service=data&request=GetFeature&data=LT_C_ADSIGG_INFO&key=인증키&domain=인증 URL&format=json&attrFilter=full_nm:like:%EC%84%9C%EC%9A%B8&geometry=false&columns=full_nm
  • 이와같이 끝에 geometry=false 를 하면 위도 경도 정보는 제외되고
  • columns= full_nm 이라고 하면
{"response" : {"service" : {"name" : "data", "version" : "2.0", "operation" : "GetFeature", "time" : "23(ms)"}, "status" : "OK", "record" : {"total" : "25", "current" : "10"}, "page" : {"total" : "3", "current" : "1", "size" : "10"}, "result" : {"featureCollection" : {"type":"FeatureCollection","bbox":[0.0,0.0,-1.0,-1.0],"features":
[
  {"type":"Feature","properties":{"full_nm":"서울특별시 종로구"},"id":"LT_C_ADSIGG_INFO.5751"}
  ,{"type":"Feature","properties":{"full_nm":"서울특별시 중구"},"id":"LT_C_ADSIGG_INFO.5752"}
  ,{"type":"Feature","properties":{"full_nm":"서울특별시 용산구"},"id":"LT_C_ADSIGG_INFO.5753"}
  ,{"type":"Feature","properties":{"full_nm":"서울특별시 성동구"},"id":"LT_C_ADSIGG_INFO.5754"}
  ,{"type":"Feature","properties":{"full_nm":"서울특별시 광진구"},"id":"LT_C_ADSIGG_INFO.5755"}
  ,{"type":"Feature","properties":{"full_nm":"서울특별시 동대문구"},"id":"LT_C_ADSIGG_INFO.5756"}
  ,{"type":"Feature","properties":{"full_nm":"서울특별시 중랑구"},"id":"LT_C_ADSIGG_INFO.5757"}
  ,{"type":"Feature","properties":{"full_nm":"서울특별시 성북구"},"id":"LT_C_ADSIGG_INFO.5758"}
  ,{"type":"Feature","properties":{"full_nm":"서울특별시 강북구"},"id":"LT_C_ADSIGG_INFO.5759"}
  ,{"type":"Feature","properties":{"full_nm":"서울특별시 도봉구"},"id":"LT_C_ADSIGG_INFO.5760"}
]
}
}}}

와 같이 시&구인 결과만 나올수 있게된다.
단 왜인지는 몰라도 full_nm:like:용산 은 먹히지 않는다 아무결과도 없음... IN을 써야하는건지



만약 검색에 여러개 조건을 쓰고 싶다면 | 를 붙여 여러개를 조회할 수 있다.

https://api.vworld.kr/req/data?service=data&request=GetFeature&data=LT_C_ADSIGG_INFO&key=인증키&domain=인증키 URL&format=json&attrFilter=sig_kor_nm:like:%EC%9A%A9%EC%82%B0|full_nm:like:%EC%84%9C%EC%9A%B8&geometry=false&columns=full_nm

위에 대한 결과는 아래와 같음

"features":[{"type":"Feature","properties":{"full_nm":"서울특별시 용산구"},"id":"LT_C_ADSIGG_INFO.5753"}]}

프로젝트에서 쓸 방식

  • 사용자에게 회원가입시 구만 입력하게 하고
    입력한 값을 sig_kor_nm(구 이름)에 변수에 넣어 반환값인 full_nm(ex.서울특별시 용산구)을 추천해준다.
    입력된 값이 대한민국에 존재하지 않는 구 라면 다음페이지로 넘어가지 못하게 하면 될듯
https://api.vworld.kr/req/data?service=data&request=GetFeature&data=LT_C_ADSIGG_INFO&key=인증키&domain=인증키 URL&format=json&attrFilter=sig_kor_nm:like:용산&geometry=false&columns=full_nm

위와같이 입력은 구 반환값은 시&구로 받아서 사용하면 될듯?
서울만 입력하면 쫘라락 구이름이 뜨는것도 좋겠지만... 구지 그럴필요가 있을까?

문제발생

ex
url attrFilter를 full_nm:like:경상남도 로했을때 아래와 같은 결과가 나온다.

"features":
[
  {"type":"Feature","properties":{"sig_cd":"48121","sig_eng_nm":"Uichang-gu, Changwon-si","full_nm":"경상남도 창원시 의창구","sig_kor_nm":"창원시 의창구"},"id":"LT_C_ADSIGG_INFO.5977"}
  ,{"type":"Feature","properties":{"sig_cd":"48123","sig_eng_nm":"Seongsan-gu, Changwon-si","full_nm":"경상남도 창원시 성산구","sig_kor_nm":"창원시 성산구"},"id":"LT_C_ADSIGG_INFO.5978"}
  ,{"type":"Feature","properties":{"sig_cd":"48125","sig_eng_nm":"Masanhappo-gu, Changwon-si","full_nm":"경상남도 창원시 마산합포구","sig_kor_nm":"창원시 마산합포구"},"id":"LT_C_ADSIGG_INFO.5979"}
  ,{"type":"Feature","properties":{"sig_cd":"48127","sig_eng_nm":"Masanhoewon-gu, Changwon-si","full_nm":"경상남도 창원시 마산회원구","sig_kor_nm":"창원시 마산회원구"},"id":"LT_C_ADSIGG_INFO.5980"}
  ,{"type":"Feature","properties":{"sig_cd":"48129","sig_eng_nm":"Jinhae-gu, Changwon-si","full_nm":"경상남도 창원시 진해구","sig_kor_nm":"창원시 진해구"},"id":"LT_C_ADSIGG_INFO.5981"}
  ,{"type":"Feature","properties":{"sig_cd":"48170","sig_eng_nm":"Jinju-si","full_nm":"경상남도 진주시","sig_kor_nm":"진주시"},"id":"LT_C_ADSIGG_INFO.5982"}
  ,{"type":"Feature","properties":{"sig_cd":"48220","sig_eng_nm":"Tongyeong-si","full_nm":"경상남도 통영시","sig_kor_nm":"통영시"},"id":"LT_C_ADSIGG_INFO.5983"}
  ,{"type":"Feature","properties":{"sig_cd":"48240","sig_eng_nm":"Sacheon-si","full_nm":"경상남도 사천시","sig_kor_nm":"사천시"},"id":"LT_C_ADSIGG_INFO.5984"}
  ,{"type":"Feature","properties":{"sig_cd":"48250","sig_eng_nm":"Gimhae-si","full_nm":"경상남도 김해시","sig_kor_nm":"김해시"},"id":"LT_C_ADSIGG_INFO.5985"}
  ,{"type":"Feature","properties":{"sig_cd":"48270","sig_eng_nm":"Miryang-si","full_nm":"경상남도 밀양시","sig_kor_nm":"밀양시"},"id":"LT_C_ADSIGG_INFO.5986"}
]
}
}}}

문제 1

  • attrFilter=full_nm:like:경상남도|sig_kor_nm:like:마산 했을때 아무 결과가 안나온다.
    대신 창원을 쓰면 결과는 나옴 문제는 서울은 sig_kor_nm에 서울특별시가 안들어가지만 경상남도는 sig_kor_nm에 창원시 진해구가 있다는것
  • 심지어 김해시는 구가 존재하지 않는다. 우리가 단기간에 밥만먹는 곳을 목적으로 한다면 상관없으나... 끼니메이트의 목적은 성향이 일치하는 사람과 좀더 멀리까지 가서 먹어도되는 즉 거주지를 벗어날정도로 멀리가야하는 맛집도 가는것을 목적으로 잡은터라.... 서울만 해당하게 할 수는 없다...

해결방법

  • 제일큰 문제는 모든 시군구 리스트를 받아올 방법이 없다는것 즉, attrFilter가 있기에 모든 시군구를 받아올 수가 없었다.

1 광역시도API 이용

https://www.vworld.kr/dev/v4dv_2ddataguide2_s002.do?svcIde=adsido
이 오픈 API에서

  • 서울~제주도까지 있는 시/도/군 리스트를
geomFilter=BOX(124,33,132,43)

이와같은 대한민국의 위도 경도 범위 (위도: 124~132 경도: 33~43)검색을 통해 모든 시/도/군을

{"type":"Feature","properties":{"ctp_eng_nm":"Seoul","ctprvn_cd":"11","ctp_kor_nm":"서울특별시"},"id":"LT_C_ADSIDO_INFO.341"}
,{"type":"Feature","properties":{"ctp_eng_nm":"Busan","ctprvn_cd":"26","ctp_kor_nm":"부산광역시"},"id":"LT_C_ADSIDO_INFO.342"}
,{"type":"Feature","properties":{"ctp_eng_nm":"Daegu","ctprvn_cd":"27","ctp_kor_nm":"대구광역시"},"id":"LT_C_ADSIDO_INFO.343"}
,{"type":"Feature","properties":{"ctp_eng_nm":"Incheon","ctprvn_cd":"28","ctp_kor_nm":"인천광역시"},"id":"LT_C_ADSIDO_INFO.344"}
,{"type":"Feature","properties":{"ctp_eng_nm":"Gwangju","ctprvn_cd":"29","ctp_kor_nm":"광주광역시"},"id":"LT_C_ADSIDO_INFO.345"}
,{"type":"Feature","properties":{"ctp_eng_nm":"Daejeon","ctprvn_cd":"30","ctp_kor_nm":"대전광역시"},"id":"LT_C_ADSIDO_INFO.346"}
,{"type":"Feature","properties":{"ctp_eng_nm":"Ulsan","ctprvn_cd":"31","ctp_kor_nm":"울산광역시"},"id":"LT_C_ADSIDO_INFO.347"}
,{"type":"Feature","properties":{"ctp_eng_nm":"Sejong-si","ctprvn_cd":"36","ctp_kor_nm":"세종특별자치시"},"id":"LT_C_ADSIDO_INFO.348"}
,{"type":"Feature","properties":{"ctp_eng_nm":"Gyeonggi-do","ctprvn_cd":"41","ctp_kor_nm":"경기도"},"id":"LT_C_ADSIDO_INFO.349"}
,{"type":"Feature","properties":{"ctp_eng_nm":"Gangwon-do","ctprvn_cd":"42","ctp_kor_nm":"강원도"},"id":"LT_C_ADSIDO_INFO.350"}
,{"type":"Feature","properties":{"ctp_eng_nm":"Chungcheongbuk-do","ctprvn_cd":"43","ctp_kor_nm":"충청북도"},"id":"LT_C_ADSIDO_INFO.351"}
,{"type":"Feature","properties":{"ctp_eng_nm":"Chungcheongnam-do","ctprvn_cd":"44","ctp_kor_nm":"충청남도"},"id":"LT_C_ADSIDO_INFO.352"}
,{"type":"Feature","properties":{"ctp_eng_nm":"Jeollabuk-do","ctprvn_cd":"45","ctp_kor_nm":"전라북도"},"id":"LT_C_ADSIDO_INFO.353"}
,{"type":"Feature","properties":{"ctp_eng_nm":"Jellanam-do","ctprvn_cd":"46","ctp_kor_nm":"전라남도"},"id":"LT_C_ADSIDO_INFO.354"}
,{"type":"Feature","properties":{"ctp_eng_nm":"Gyeongsangbuk-do","ctprvn_cd":"47","ctp_kor_nm":"경상북도"},"id":"LT_C_ADSIDO_INFO.355"}
,{"type":"Feature","properties":{"ctp_eng_nm":"Gyeongsangnam-do","ctprvn_cd":"48","ctp_kor_nm":"경상남도"},"id":"LT_C_ADSIDO_INFO.356"}
,{"type":"Feature","properties":{"ctp_eng_nm":"Jeju-do","ctprvn_cd":"50","ctp_kor_nm":"제주특별자치도"},"id":"LT_C_ADSIDO_INFO.357"}]}
}}}

이와 같이 뽑아온다. 이 리스트를 selectbox로 회원이 선택하게 한다음 선택된 값을 기존의 시/군/구 오픈API에서 full_nm:like: 값에 넣는다. 그러면 경기도를 예로들어 sig_kor_nm값만을 출력하여 경기도에 소속된 시/구 리스트를 얻는다. 단, 서울과 같은 광역시 특별시는 sig_kor_nm은 구 리스트만 얻어낼것
{"type":"Feature","properties":{"sig_kor_nm":"수원시 장안구"},"id":"LT_C_ADSIGG_INFO.5826"}
,{"type":"Feature","properties":{"sig_kor_nm":"수원시 권선구"},"id":"LT_C_ADSIGG_INFO.5827"}
,{"type":"Feature","properties":{"sig_kor_nm":"수원시 팔달구"},"id":"LT_C_ADSIGG_INFO.5828"}
,{"type":"Feature","properties":{"sig_kor_nm":"수원시 영통구"},"id":"LT_C_ADSIGG_INFO.5829"}
,{"type":"Feature","properties":{"sig_kor_nm":"성남시 수정구"},"id":"LT_C_ADSIGG_INFO.5830"}
,{"type":"Feature","properties":{"sig_kor_nm":"성남시 중원구"},"id":"LT_C_ADSIGG_INFO.5831"}
,{"type":"Feature","properties":{"sig_kor_nm":"성남시 분당구"},"id":"LT_C_ADSIGG_INFO.5832"}
,{"type":"Feature","properties":{"sig_kor_nm":"의정부시"},"id":"LT_C_ADSIGG_INFO.5833"}
,{"type":"Feature","properties":{"sig_kor_nm":"안양시 만안구"},"id":"LT_C_ADSIGG_INFO.5834"}
,{"type":"Feature","properties":{"sig_kor_nm":"안양시 동안구"},"id":"LT_C_ADSIGG_INFO.5835"}
,{"type":"Feature","properties":{"sig_kor_nm":"부천시"},"id":"LT_C_ADSIGG_INFO.5836"}
,{"type":"Feature","properties":{"sig_kor_nm":"광명시"},"id":"LT_C_ADSIGG_INFO.5837"}
,{"type":"Feature","properties":{"sig_kor_nm":"평택시"},"id":"LT_C_ADSIGG_INFO.5838"}
,{"type":"Feature","properties":{"sig_kor_nm":"동두천시"},"id":"LT_C_ADSIGG_INFO.5839"}
,{"type":"Feature","properties":{"sig_kor_nm":"안산시 상록구"},"id":"LT_C_ADSIGG_INFO.5840"}
,{"type":"Feature","properties":{"sig_kor_nm":"안산시 단원구"},"id":"LT_C_ADSIGG_INFO.5841"}
,{"type":"Feature","properties":{"sig_kor_nm":"고양시 덕양구"},"id":"LT_C_ADSIGG_INFO.5842"}
,{"type":"Feature","properties":{"sig_kor_nm":"고양시 일산동구"},"id":"LT_C_ADSIGG_INFO.5843"}
,{"type":"Feature","properties":{"sig_kor_nm":"고양시 일산서구"},"id":"LT_C_ADSIGG_INFO.5844"}
,{"type":"Feature","properties":{"sig_kor_nm":"과천시"},"id":"LT_C_ADSIGG_INFO.5845"}
,{"type":"Feature","properties":{"sig_kor_nm":"구리시"},"id":"LT_C_ADSIGG_INFO.5846"}
,{"type":"Feature","properties":{"sig_kor_nm":"남양주시"},"id":"LT_C_ADSIGG_INFO.5847"}
,{"type":"Feature","properties":{"sig_kor_nm":"오산시"},"id":"LT_C_ADSIGG_INFO.5848"}
,{"type":"Feature","properties":{"sig_kor_nm":"시흥시"},"id":"LT_C_ADSIGG_INFO.5849"}
,{"type":"Feature","properties":{"sig_kor_nm":"군포시"},"id":"LT_C_ADSIGG_INFO.5850"}
,{"type":"Feature","properties":{"sig_kor_nm":"의왕시"},"id":"LT_C_ADSIGG_INFO.5851"}
,{"type":"Feature","properties":{"sig_kor_nm":"하남시"},"id":"LT_C_ADSIGG_INFO.5852"}
,{"type":"Feature","properties":{"sig_kor_nm":"용인시 처인구"},"id":"LT_C_ADSIGG_INFO.5853"}
,{"type":"Feature","properties":{"sig_kor_nm":"용인시 기흥구"},"id":"LT_C_ADSIGG_INFO.5854"}
,{"type":"Feature","properties":{"sig_kor_nm":"용인시 수지구"},"id":"LT_C_ADSIGG_INFO.5855"}
,{"type":"Feature","properties":{"sig_kor_nm":"파주시"},"id":"LT_C_ADSIGG_INFO.5856"}
,{"type":"Feature","properties":{"sig_kor_nm":"이천시"},"id":"LT_C_ADSIGG_INFO.5857"}
,{"type":"Feature","properties":{"sig_kor_nm":"안성시"},"id":"LT_C_ADSIGG_INFO.5858"}
,{"type":"Feature","properties":{"sig_kor_nm":"김포시"},"id":"LT_C_ADSIGG_INFO.5859"}
,{"type":"Feature","properties":{"sig_kor_nm":"화성시"},"id":"LT_C_ADSIGG_INFO.5860"}
,{"type":"Feature","properties":{"sig_kor_nm":"광주시"},"id":"LT_C_ADSIGG_INFO.5861"}
,{"type":"Feature","properties":{"sig_kor_nm":"양주시"},"id":"LT_C_ADSIGG_INFO.5862"}
,{"type":"Feature","properties":{"sig_kor_nm":"포천시"},"id":"LT_C_ADSIGG_INFO.5863"}
,{"type":"Feature","properties":{"sig_kor_nm":"여주시"},"id":"LT_C_ADSIGG_INFO.5864"}
,{"type":"Feature","properties":{"sig_kor_nm":"연천군"},"id":"LT_C_ADSIGG_INFO.5865"}
,{"type":"Feature","properties":{"sig_kor_nm":"가평군"},"id":"LT_C_ADSIGG_INFO.5866"}
,{"type":"Feature","properties":{"sig_kor_nm":"양평군"},"id":"LT_C_ADSIGG_INFO.5867"}]}
}}}

이와 같은 결과값을 " "를 기준으로 두개 값 or 한개값으로 분류한다. 즉 시와 구를 나누는것
그리고 이들 리스트 중에 선택할 수 있게할 예정이다.

아근데 차라리 광역시도 선택하고 나머지는 리스트에서 검색할수 있게하는게?....날듯? 다시보니 데이터 종류가 시| 군 | 시+구 이렇게 나눠져있어서 선택하게 만드는게 좀 이상할거같다.

첫번째 에러

  • window.onload를 사용해 회원가입 페이지 로딩후 광역시도 api를 다음과 같이 호출했다.
<script>
  window.onload = function()
	{
	//alert(); 호출확인
	
	$.ajax(
			{
				type:"GET"
				,url:"https://api.vworld.kr/req/data?service=data&request=GetFeature&data=LT_C_ADSIDO_INFO&key=5EFC480E-69E8-37A1-852A-43F279EA8BC7&domain=39.123.28.118&geometry=false&size=100&geomFilter=BOX(124,33,132,43)"
				,dataType:"jsonp"
				,success: function(data)
				{
					alert(data.result);
					
				}
				,error: function(e)
				{
					alert(e.responseText);
					
				}
				
			});
	}
  </script>

그리고
Access to XMLHttpRequest at 'API주소' from origin 'http://localhost:8090' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
와 같은 에러가 발생했다.

참고한 페이지는
https://coding-groot.tistory.com/91
https://kimyhcj.tistory.com/263
https://inpa.tistory.com/entry/WEB-%F0%9F%93%9A-CORS-%F0%9F%92%AF-%EC%A0%95%EB%A6%AC-%ED%95%B4%EA%B2%B0-%EB%B0%A9%EB%B2%95-%F0%9F%91%8F

헤더,url 참고페이지
https://velog.io/@pixelstudio/%ED%81%AC%EB%A1%AC-%EA%B0%9C%EB%B0%9C%EC%9E%90-%EB%8F%84%EA%B5%AC%EB%A1%9C-%EB%B3%B4%EB%8A%94-HTTP-%ED%97%A4%EB%8D%94-%EC%95%8C%EC%95%84%EB%B3%B4%EA%B8%B0

결국 dataType : jsonp 로 바꿔 해결하였다.
출처 : 브이월드 Q&A
https://www.vworld.kr/v4po_brdqna_s002.do?pageIndex=1&searchCondition=4&searchKeyword=CORS&bodIde=&brdIde=21576&bodCde=QNA&fileCheck=Y&repyCheck=Y

3반환데이터 사용법

3-1광역시도 선택시 select의 option태그 생성

  • 그림에서 찾기 버튼 클릭시 아래와 같은 스크립트가 실행되어 광역시도 데이터를 받아와 select의 option 태그를 생성한다.

  • 찾기 버튼의 id = loadIntModal
    select의 id = city_province_list_Int

    .empty를 사용하여 select안의 내용을 삭제
    .append를 사용하여 select안에 option 태그 생성

<script>
      $("#loadIntModal").click(function()   //회원가입페이지에서 찾기 버튼을 눌렀을때 광역시도 데이터 load
		{
	    	$("#city_province_list_Int").empty();  //select 의 option을 모두 삭제 #city_province_list_Int는 select의 아이디
	    	
	    	$
			.ajax(
			{
				type : "GET",
				url : "http://api.vworld.kr/req/data?service=data&request=GetFeature&data=LT_C_ADSIDO_INFO&key=&domain=&geometry=false&size=100&geomFilter=BOX(124,33,132,43)",
				dataType : "jsonp",
				success : function(data)
				{
					let city_province_option = "<option selected='selected'>선택</option>";

					//alert(data); //Object
					//alert(data.response); //[object Object]
					//alert(data.response.status); //OK 실제로 status라는 값은 OK
					//alert(data.response.result.featureCollection); //[object Object] 결과값이 들어있는 result 이름의 Object 안에 있는 featureCollection이라는 이름의 객체로 
					//type":"FeatureCollection","bbox","features" 세가지 변수(?)를 가지고있다.

					//alert(data.response.result.featureCollection.features); //전국 광역시 결과값을 내포하고 있는 결과값 변수
					/*
					[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],
					[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],
					[object Object],[object Object],[object Object]
					 */

					//결과값을 가지는 객체배열을 dataList라는 변수에 주입
					const dataList = data.response.result.featureCollection.features;

					//alert(dataList.length); //17 광역시도의 개수도 17

					//alert(dataList[0].properties.ctp_kor_nm);// 서울 특별시  / features의 0번째 배열값의 properties중 광역시도이름인 ctp_kor_nm의 값 = 서울특별시

					//모든 광역시도를 option으로 담는다
					//for문 변수는 const를 지정하지 않는다. const는 한번 할당한 값을 다시 할당하지 못한다.
					for (let i = 0; i < dataList.length; i++)
					{
						//alert(dataList[i].properties.ctp_kor_nm);

						//제주특별자치도, 세종특별자치시 는 카카오맵에서도 동일하게 나온다.
						//충청남도,북도  경상남도 북도 전라남도 북도 는 충남 충북 처럼  1과 3번째 글자가 조합되고 나머지는 없어진다. 즉 남도,북도가 들어가면 가져와서 1,3글자만 연결해서 넣으면 될듯
						//강원도, 경기도도 도가 없어진다.
						//1.남도, 북도를 가지고있다면 1번째 3번째 글자만 떼내어 연결시킨다.
						//ㄴㄴㄴㄴㄴ 글자로 할필요가 없다.

						//ctprvn_cd(행정구역코드)  11 = 서울특별시                              ※ 특별시 삭제
						//                         26~31 = 부산,대구,인천,광주,대전,울산광역시  ※ 광역시 삭제
						//                         36 = 세종특별자치시                          ※ 그대로
						//                         41~42 = 경기도, 강원도                       ※'도' 빼기
						//                         43~48 = 충청북도~ 경상남도                   ※ 1번째 3번째 단어 결합시켜넣기
						//                         50 = 제주특별자치도                          ※그대로

						//광역시의 행정구역 코드
						let ctprvn_cd = parseInt(dataList[i].properties.ctprvn_cd);
						let ctp_kor_nm = dataList[i].properties.ctp_kor_nm;

						/* if (ctprvn_cd == 11)
						{
							ctp_kor_nm = ctp_kor_nm.replace("특별시", "");

						} else if (26 <= ctprvn_cd && ctprvn_cd <= 31)
						{
							ctp_kor_nm = ctp_kor_nm.replace("광역시", "");
						} else if (41 <= ctprvn_cd && ctprvn_cd <= 42)
						{
							ctp_kor_nm = ctp_kor_nm.replace("도", "");
						} else if (43 <= ctprvn_cd && ctprvn_cd <= 48)
						{
							ctp_kor_nm = ctp_kor_nm.substr(0, 1)
									+ ctp_kor_nm.substr(2, 1);
						}
 */
						city_province_option += "<option value="+ctp_kor_nm+">";
						city_province_option += dataList[i].properties.ctp_kor_nm;
						city_province_option += "</option>";
					}

					$("#city_province_list_Int").append(city_province_option);

				},
				error : function(e)
				{
					alert(e.responseText);

				}

			});
			
		});
  </script>

결과는 이와 같다.

if else의 주석을 해제하면

이와같이 보이는건 특별시,광역시가 붙어있으나 value에는 카카오맵에서

쓰이는 값처럼 서울,인천,제주특별자치도 에 맞춘 값이 들어간다. value와 text가 다른이유는
시군구 API사용시 충남,충북, 이런식으로는 검색이 안되고 충청북도 충청남도와 같이 sig_kor_nm을 검색값으로 지정해야 하기 때문에 text를 이용해 검색해야하기 때문

  • $("#city_province_list_Int").empty()
    지역을 검색하는 모달창을 껏다켰을때 기존에 불러왔던 광역시데이터가 중복되지 않게 하기위한 select의 option 전체 삭제




3-2 광역시도 선택시 해당 광역시도의 전체 시/군/구 데이터 가져오기

  • 광역시도를 select로 선택하면 밑의 div에 선택한 광역시 의 시/군/구 전체 리스트가 뜨게 하고 싶다.
$("#city_province_list").change(
				function()
				{
					search();

				});
		
		
		function search()
		{
			$("#User_addrRec").empty();
			//alert();

			//&attrFilter=full_nm:like: | sig_kor_nm:like:			
			
			params = "attrFilter=full_nm:like:"
					+ $("#city_province_list option:checked").text();  //https://api.jquery.com/checked-selector/참고
			
			
			$.ajax(
					{

						type : "GET",
						url : "https://api.vworld.kr/req/data?service=data&request=GetFeature&data=LT_C_ADSIGG_INFO&key="
								+ "&domain=&geometry=false&size=100&columns=sig_kor_nm",
						data : params,
						dataType : "jsonp",
						success : function(data)
						{
							let city_county_rec=""; //받아온 시군구 리스트
							//city ​​county
							const city_county_list = data.response.result.featureCollection.features;
																			
							//alert(city_county_list.length);
							//alert(city_county_list[0].properties.sig_kor_nm);
							
							for(let i=0;i<city_county_list.length;i++)
							{
								city_county_rec += "<button type='button' class='btn rounded' style='margin:auto;display:block;' onclick='insertRegion(this)'>"
								+ (($("#city_province_list option:checked").text() == city_county_list[i].properties.sig_kor_nm) ? city_county_list[i].properties.sig_kor_nm+"</button>" : $("#city_province_list option:checked").val()+" "+city_county_list[i].properties.sig_kor_nm+"</button>");
								city_county_rec += "<hr>";
								
								
								
								
							}
							
							
							
							$("#User_addrRec").html(city_county_rec);
							

						},
						error : function(e)
						{
							alert(e.responseText);

						}
					});
			
		}
</script>
  • $("#User_addrRec").empty() 를 사용한 이유는 div내용을 지우지 않을시 div내용이 중첩되서 나와서
  • $("#city_province_list").change는 select가 변화되었을때 기존 select의 option을 없애고 새로 선택된 광역시도의 시/군/구 리스트를 불러오는 search()메소드를 호출하게 한다.

-세종특별시 같은 경우엔 소속된 시/군/구가 없어 세종특별시 세종특별시 가 나오므로 삼항연산자를 이용하여 full_nm 과 sig_kor_nm이 같을경우 sig_kor_nm만 출력하도록 만들었다.




3-3 선택한 광역시도에서 시/군/구 데이터 입력시

충남과 같이 시/군/구가 많을 경우에는 타이핑으로 찾는게 사용자 관점에서 편리하므로

  • 이와같이 사용자가 타이핑한 내용과 같은 데이터를 보여줄 수 있도록
    .keyup()과 시/군/구 api를 아래와 같이 사용한다.
<script>
   $("#User_addrDetail").keyup(
						function()
						{
							
							if($.trim($("#User_addrDetail").val())=="") //사용자가 데이터를 전부 지웠을 경우 즉 빈칸인 경우 다시 
								{
								search();
								}
							
							
							else{
								
								$("#User_addrRec").empty();
								//alert();

								//&attrFilter=full_nm:like: | sig_kor_nm:like:			
								
								params = "attrFilter=full_nm:like:"
										+ $("#city_province_list option:checked").text()  //https://api.jquery.com/checked-selector/참고
										+ "|" 
										+ "sig_kor_nm:like:"+$("#User_addrDetail").val();
								
								
								$.ajax(
										{

											type : "GET",
											url : "https://api.vworld.kr/req/data?service=data&request=GetFeature&data=LT_C_ADSIGG_INFO&key="
													+ "&domain=&geometry=false&size=100&columns=sig_kor_nm",
											data : params,
											dataType : "jsonp",
											success : function(data)
											{
												let city_county_rec=""; //받아온 시군구 리스트
												//city ​​county
												const city_county_list = data.response.result.featureCollection.features;
																								
												//alert(city_county_list.length);
												//alert(city_county_list[0].properties.sig_kor_nm);
												
												for(let i=0;i<city_county_list.length;i++)
												{
													
													city_county_rec += "<button type='button' class='btn rounded' style='margin:auto;display:block;' onclick='insertRegion(this)'>"
													+ (($("#city_province_list option:checked").text() == city_county_list[i].properties.sig_kor_nm) ? city_county_list[i].properties.sig_kor_nm+"</button>" : $("#city_province_list option:checked").val()+" "+city_county_list[i].properties.sig_kor_nm+"</button>");
													city_county_rec += "<hr>";
													
													}
												
												
												
												$("#User_addrRec").html(city_county_rec);

											},
											error : function(e)
											{
												alert(e.responseText);

											}
										});
								
								
							}
							
							
							

						});
  </script>

params으로 3-1에서 선택한 광역시도를 option:checked 를 통해 받아오고 full_nm에 넣은후 시/군/구를 담당하는 sig_kor_nm에는 사용자가 입력한 값을 넣어 ajax 처리를 한다.

:checked 참고 https://api.jquery.com/checked-selector/#checked1

결과는

이와 같다.

다만 시군구 api의 한계로

이와 같이 sig_kor_nm이 시+구 인경우는 동남구 만 입력하면 결과가 나오지 않는다.

3-4 사용자의 주소 입력방식

api를 이용해 광역시도 및 시군구 데이터를 가져왔다 해도 사용자가 입력한 데이터를 이용하는 방식은 옳지않다고 생각해 클릭해서 주소를 등록할 수 있도록 클릭시

<script>
  function insertRegion(region)
	{
		//alert($(region).text());
		
		$("#User_addr").val($(region).text());
		$("#regionModal").modal("hide");
		
	}

  </script>

아래와 같은 함수를 실행시켜 회원가입페이지의 주소창에 입력되게 하고 .modal("hide")을 이용해 클릭시 모달창이 닫히도록 하였다.

3-5 구단위 검색 가능하게

https://api.jquery.com/contains-selector/#contains1

https://api.jquery.com/children/#children-selector

https://api.jquery.com/find/

https://api.jquery.com/contents/

0개의 댓글