직업훈련/새싹(SeSAC)

[새싹(SeSAC) 프론트엔드] day22 221115

뉼👩🏻‍💻 2022. 11. 16. 09:10
728x90
반응형
SMALL

 

API 

(Application Programming Interface)

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

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

 

Open API

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

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

- 제공처 : 네이버, 구글, 카카오 

 

 

 

URL에 넣는 주소 

➡️ 현재 위도, 경도 값을 주면 그것에 맞는 날씨를 알려주는 방식

 

<날씨 정보를 가져오는 방법>

1.도시 이름 (by city name)

2. 도시 아이디(by city ID)

3. 도시 위치(by geographic coordinates)

4. zip code (by zip code)

 

 

latitude : 위도

longitude :경도  

API Key : 사용자의 API키

 

 

 

navigator.geolocation

:js에서 사용. 웹에서 장치의 위치 정보를 담은 Geolocation 객체를 반환

 

.getCurrentPosition(success, error)
// success : 위치 정보 추출 성공 시 실행되는 콜백 함수 
// error : 위치 정보 추출 실패 시 실행되는 콜백함수 

 

 

 

 

 

(*)실습

[코드]

const API_KEY = "######";

navigator.geolocation.getCurrentPosition(onGeoLocation, onGeoError);

function onGeoLocation(position) {
  //position : 위치 정보를 담은 객체
  console.log(position);

  const lat = position.coords.latitude; //위도
  const lon = position.coords.longitude; //경도

  const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=metric`;

  fetch(url)
    .then((response) => response.json())
    .then((data) => {
      const weatherImg = document.querySelector("#weather .wimg");
      const weatherTemp = document.querySelector("#weather .temp");
      const weatherInfo = document.querySelector("#weather .info");
      const weatherCity = document.querySelector("#weather .city");

      weatherImg.src = `/img/${data.weather[0].main}.png`;
      weatherTemp.innerHTML = `${Math.ceil(data.main.temp)}'C`;
      weatherInfo.innerHTML = `${data.weather[0].main}`;
      weatherCity.innerHTML = data.name;
    });
}

function onGeoError() {
  console.log("에러");
}

 

[결과]

 

 

 

 

 

 

따릉이 대여소 정보 

http://data.seoul.go.kr/dataList/OA-15493/A/1/datasetView.do

 

열린데이터광장 메인

데이터분류,데이터검색,데이터활용

data.seoul.go.kr

[코드]

const API_KEY = "############";
const url = `http://openapi.seoul.go.kr:8088/${API_KEY}/json/bikeList/1/5/`;

fetch(url)
  .then((response) => response.json())
  .then((data) => {
    console.log(data);
    console.log(data["rentBikeStatus"]["row"]);
    console.log(data.rentBikeStatus.row);
    let stationNameArr = [];
    let latArr = [];
    let lonArr = [];
    for (let i = 0; i < data.rentBikeStatus.row.length; i++) {
      stationNameArr.push(data.rentBikeStatus.row[i].stationName);
      latArr.push(data.rentBikeStatus.row[i].stationLatitude);
      lonArr.push(data.rentBikeStatus.row[i].stationLongitude);
    }
    console.log(stationNameArr);
    console.log(latArr);
    console.log(lonArr);
  })
  .catch((error) => console.log(error));

 

[결과]

 

 

카카오지도 

(*)실습

<!DOCTYPE html>
<html lang="ko">
  <head>
    <meta charset="UTF-8" />
    <title>카카오 지도 API 불러오기</title>
    <link rel="stylesheet" href="" />
  </head>
  <body>
    <div id="map" style="width: 100%; height: 350px"></div>
    <script
      type="text/javascript"
      src="//dapi.kakao.com/v2/maps/sdk.js?appkey=######"
    ></script>
    <script src="js/bicycleMap.js"></script>
  </body>
</html>
var mapContainer = document.getElementById("map"), // 지도를 표시할 div
  //지도 옵션
  mapOption = {
    // 지도의 중심좌표 (위도, 경도)
    center: new kakao.maps.LatLng(33.450701, 126.570667),

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

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

console.log(map);

 

[결과]

 

 

 

(*) 카카오 지도에 자전거 대여소 정보 마크 표시하기 

[코드]

// // 지도를 표시할 div
// var mapContainer = document.getElementById("map");
// //지도 옵션
// var mapOption = {
//   // 지도의 중심좌표 (위도, 경도)
//   center: new kakao.maps.LatLng(33.450701, 126.570667),

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

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

const API_KEY = "#####";
const url = `http://openapi.seoul.go.kr:8088/${API_KEY}/json/bikeList/1/5/`;

fetch(url)
  .then((response) => response.json())
  .then((data) => {
    let rows = data.rentBikeStatus.row;
    let stationList = [];

    for (let i = 0; i < data.rentBikeStatus.row.length; i++) {
      stationName = rows[i].stationName;
      stationLat = rows[i].stationLatitude;
      stationLon = rows[i].stationLongitude;

      stationInfo = {
        stationName: stationName,
        stationLat: stationLat,
        stationLon: stationLon,
      };
      stationList.push(stationInfo);
    }
    console.log(stationList);

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

    // 위치 정보를 저장
    stationList.forEach((info) => {
      positions.push({
        latlng: new kakao.maps.LatLng(info.stationLat, info.stationLon),
        title: info.stationName,
      });
      // 지도 출력 기능을 가진 함수 호출
      showMap(positions);
    });
    console.log(positions);
  })
  .catch((error) => console.log(error));

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주차 블로그 포스팅(화)

728x90
반응형