본문 바로가기

Javascript

[새싹 프론트엔드] 5주차 - 2

API(Application Programming Interface)

• 응용 프로그램에서 데이터를 주고 받기 위한 방법

• API 사용 시, 개발 시간 및 비용 절감 가능

 

Open API

• 누구나 사용할 수 있도록 공개된 API

• 지도, 날씨, 음악, 공공데이터, 쇼핑 등 다양한 분야에서 사용 가능

• 제공처 (네이버, 카카오, 구글 등)

 

날씨 API

https://openweathermap.org/

 

Сurrent weather and forecast - OpenWeatherMap

Access current weather data for any location on Earth including over 200,000 cities! The data is frequently updated based on the global and local weather models, satellites, radars and a vast network of weather stations. how to obtain APIs (subscriptions w

openweathermap.org

 

회원가입 → 개인 API KEY 발급 / 확인 → 상단 API 메뉴 선택

 

API 사용 설명 페이지

 

API call

위도, 경도 값으로 날씨 api 호출하기

`https://api.openweathermap.org/data/2.5/weather? lat=${lat}&lon=${lon}&appid=${API key}&units=metric`

• lat : 위도

• lon : 경도

• API Key : 사용자의 API 키

 

navigator.geolocation

• 웹에서 장치의 위치 정보를 담은 Geolocation 객체를 반환

 

• .getCurrentPosition(success, error)

    • 장치의 현재 위치를 GeolocationPosition 객체로 반환

    • success

         • 위치 정보 추출 성공 시 실행되는 콜백함수

    • error

         • 위치 정보 추출 실패 시 실행되는 콜백함수

 

위치 정보 얻어오기

index.js

 

position 객체

1.도시 이름 ( By City Name)

2. 도시 아이디 ( By City ID)

3. 도시 위치 (경도, 위도) (By Geographic coordination)

4. zipcode(Byzipcode)

 

API 호출 및 처리

index.js

 

data 객체

 

index.js

위치 정보 추출 실패 시 처리하는 함수

 

main.html

 

실행 결과

 


 

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

서울 열린데이터 광장 회원가입 → 인증키 발급

 

API Call

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

 

대여소 정보 5개 호출하기

 

실행 결과)

 

대여소 정보만 가져오기

 

실행 결과)

 

 

대여소 이름(stationName)만 가져오기

 

실행 결과

 

카카오 지도 API

• 상단 메뉴 → 내 애플리케이션 → 애플리케이션 추가하기 → 플랫폼 설정하기 Web → 플랫폼 등록

• 상단 메뉴 → 문서 → 지도/로컬 API 가이드 → sample → 지도 생성하기

 

HTML 파일

• 지도 출력할 영역 생성

• 카카오 지도 API 연결

 

JS 파일

 

실행 결과

 

서울시 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);
}

 

서울시 공공자전거 대여소 지도에 표시

지도 출력 기능 함수 구현

 

실행 결과)

 

 

 

 

 

 

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