[새싹 프론트엔드] API

Ryu·2022년 11월 17일

새싹

목록 보기
18/36

API

API란?

API(Application Programming Interface)

  • 응용 프로그램에서 데이터를 주고 받기 위한 방법
  • API 사용 시, 개발 시간 및 비용 절감 가능

Open API

  • 누구나 사용할 수 있도록 공개된 API
  • 지도, 날씨, 음악, 공공데이터, 쇼핑 등 다양한 분야에서 사용 가능
  • 제공처
    • 네이버, 카카오, 구글

날씨 API

API call

  • 위도, 경도 값으로 날씨 api 호출하기
https://api.openweathermap.org/data/2.5/weather?
lat=**{lat}**&lon=**{lon}**&appid=**{API key}**&units=metric

units=metric: 섭씨 온도로 변환
날씨 정보 가져오는 방법
1. 도시 이름(By City Name)
2. 도시 아이디(By City ID)
3. 도시 위치(위도, 경도) (By Geographic Coordinates)
4. ZIP code(By ZIP Code)
  • lat: 위도
  • lon: 경도
  • API Key: 사용자의 API 키
  • 웹에서 장치의 위치 정보를 담은 Geolocation 객체를 반환
  • .getCurrentPosition(success, error)
    • 장치의 현재 위치를 GeolocationPosition 객체로 반환
    • success
      • 위치 정보 추출 성공 시 실행되는 콜백함수
    • error
      • 위치 정보 추출 실패 시 실행되는 콜백함수

위치 정보 얻어오기

  • index.js
// API KEY
const API_KEY = "본인의 API KEY"; 

// 장치의 현재 위치 추출
navigator.geolocation.getCurrentPosition(onGeoLocation, onGeoError);

function onGeoLocation(position) { 
		// position : 위치 정보를 담은 객체 
		console.log(position);
		
		const lat = position.coords.latitude; // 위도
		const lon = position.coords.longitude; // 경도 
}
  • position 객체

API 호출 및 처리

  • index.js
// API 호출 경로
const url = `https://api.openweathermap.org/data/2.5/weather?
             lat=${lat}&lon=${lon}&appid=${API_KEY}&units=metric`;

// URL 처리 
fetch(url)
    .then((response) => response.json())
    .then((data) => {
			const weatherImg = document.querySelector("#weather .wImg"); const weather = document.querySelector("#weather .temp"); const info = document.querySelector("#weather .info");
			const city = document.querySelector("#weather .city");

			// HTML 태그에 데이터 넣기
			weatherImg.src = "./mist_icon.png"; 
			weather.innerHTML = `${Math.ceil(data.main.temp)}°C`; 
			info.innerHTML = `${data.weather[0].main}`; 
			city.innerHTML = data.name;
});
  • data 객체
  • index.js
    • 위치 정보 추출 실패 시 처리하는 함수

      function onGeoError() { 
      	alert("위치를 찾을 수 없습니다.");
      }
  • main.html
<div id="weather">
	<img class="wImg" src=""> 
	<div class="temp"></div> 
	<div class="info"></div> 
	<div class="city"></div>
</div>
<script src="./index.js" />

서울시 공공 API - 공공 자전거 정보

서울 열린 데이터 광장

API call

"http://openapi.seoul.go.kr:8088/개인인증키/json/bikeList/1/5/"

[실습] 서울시 공공자전거 정보 가져오기

  • 대여소 정보 5개 호출하기
fetch( "http://openapi.seoul.go.kr:8088/개인인증키/json/bikeList/1/5/" )
	.then((response) => response.json())
	.then((data) => {
     console.log(data);
  })
  .catch((error) => console.log(error));
  • 대여소 정보만 가져오기
fetch("http://openapi.seoul.go.kr:8088/개인인증키/json/bikeList/1/5/" )
	.then((response) => response.json())
	.then((data) => {
     let rows = data["rentBikeStatus"]["row"];
     console.log(rows);
  })
  .catch((error) => console.log(error));
  • 대여소 이름(stationName)만 가져오기
fetch( "http://openapi.seoul.go.kr:8088/개인인증키/json/bikeList/1/5/" )
	.then((response) => response.json())
	.then((data) => {
     let rows = data["rentBikeStatus"]["row"];

		 rows.forEach((row) => {
				let stationName = row["stationName"]; 
				console.log(stationName);
				});
  })
  .catch((error) => console.log(error));

카카오 지도 API

카카오 개발자센터

[실습] 카카오 지도 띄우기

  • HTML 파일
    • 지도 출력할 영역 생성
    • 카카오 지도 API 연결
<div id="map" style="width: 100%; height: 500px"></div>

<script type="text/javascript" 
		src="//dapi.kakao.com/v2/maps/sdk.js?appkey=개인인증키">
</script>
  • js 파일
// 지도 표시 영역
let mapContainer = document.getElementById("map");

// 지도 옵션
let mapOption = {
		// 지도 중심좌표
		center: new kakao.maps.LatLng(33.450701, 126.570667),

		// 지도 확대 레벨
		level: 3 
};

// 지도를 표시할 div와 지도 옵션으로 지도를 생성
let map = new kakao.maps.Map(mapContainer, mapOption);

[실습] 서울시 공공자전거 대여소 지도에 표시

  • 서울시 API 를 호출하여 공공자전거 대여소 정보 얻기
let stationList = [];

fetch( http://openapi.seoul.go.kr:8088/개인인증키/json/bikeList/1/5/)
	.then((response) => response.json())
	.then(data => {
	    let rows = data["rentBikeStatus"]["row"];
			// 정거장, 위도/경도 저장 
			rows.forEach((row) => {
				stationName = row["stationName"]; 
				stationLatitude = row["stationLatitude"]; 
				stationLongitude = row["stationLongitude"];

	// 정거장 정보(stationInfo) 객체 생성 
	stationInfo = {
		stationName: stationName,
		stationLatitude: stationLatitude, // 위도 
		stationLongitude: stationLongitude, // 경도
	};
	
	// 정거장 정보(stationInfo)를 stationList 배열에 추가
	stationList.push(stationInfo);
});
  • 카카오 지도 API 포맷으로 위치 정보 저장
fetch( http://openapi.seoul.go.kr:8088/개인인증키/json/bikeList/1/5/) 
.then((response) => response.json())
.then(data => {
		 // 생략

     // 위치 정보를 저장할 positions 배열
     let positions = [];

     // 위치 정보를 저장 
     stationList.forEach((info) => {
        positions.push({
          latlng: new kakao.maps.LatLng(
                      info.stationLatitude,
                      info.stationLongitude
					),
					title: info.stationName, 
				});
		});
		 // 지도 출력 기능을 가진 함수 호출
     showMap(positions);
});
  • 지도 출력 기능 함수 구현
function showMap(positions) {
	// 지도 표시 영역
	let mapContainer = document.getElementById("map");
	
	// 지도 옵션
	let mapOption = {
		center: new kakao.maps.LatLng(37.5556488, 126.91062927), 
		level: 3,
		marker: positions,
	};

	// 지도를 표시할 div와 지도 옵션으로 지도를 생성
	let map = new kakao.maps.Map(mapContainer, mapOption); 

	// 이미지 마커 경로 
	let imageSrc =
	    https://t1.daumcdn.net/localimg/localimages/07/mapapidoc/markerStar.png;
	// 이미지 마커 표시
	positions.forEach((item) => {
		let imageSize = new kakao.maps.Size(24, 35);
		let markerImage = new kakao.maps.MarkerImage(imageSrc, imageSize);
		
	// 마커 생성
	let marker = new kakao.maps.Marker({
		map: map, // 마커를 표시할 지도 
		position: item.latlng, // 마커를 표시할 위치 
		title: item.title, // 마커 타이틀 
		image: markerImage, // 마커 이미지
			});
		});
}

새싹DT 기업연계형 프론트엔드 실무 프로젝트 과정 5주차 블로그 포스팅

0개의 댓글