Riucc's Storage
RSS
태그
관리
쓰기
카테고리
  • IT (593)
    • 정리 (0)
    • C# (42)
    • ASP.NET MVC (16)
    • JQuery&Javascript (12)
    • CSS (11)
    • 데이터베이스 (32)
    • Windows Server (6)
    • Active Directory (3)
    • Exchange (9)
    • JAVA (2)
    • JSP (39)
    • JSP 게시판 만들기 (21)
    • JSP 개발 참고 (15)
    • JSP 안드로이드 (4)
    • Servlet (17)
    • Spring (42)
    • HTML (14)
    • NodeJS (46)
    • MongoDB (11)
    • 리눅스 (18)
    • 자료구조 (16)
    • 아이폰 (24)
    • 안드로이드 (68)
    • API 활용하기 (10)
    • 소켓네트워크 (28)
    • 라즈베리파이 (11)
    • AWS클라우드 (10)
    • 빅데이터Hadoop (22)
    • 커널모듈프로그래밍 (8)
    • 기타 (10)
    • 자격증 (26)
Riucc's Storage

[안드로이드] - Mapbox API 이용해 지도 및 길찾기 구현하기

안드로이드|2018. 5. 31. 13:40
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

○ Mapbox API 이용해 지도 및 길찾기 구현하기 

 

1. build.gradle (Moudle: app) 에 추가


dependencies {

    implementation 'com.mapbox.mapboxsdk:mapbox-sdk-services:3.1.0'

    implementation 'com.mapbox.mapboxsdk:mapbox-android-sdk:6.1.3'

}


2. AndroidManifest.xml 에 권한 추가


<uses-permission android:name="android.permission.INTERNET"/>

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />


3. res-values-strings.xml 에 접근 토큰 추가(Mapbox 홈페이지 가입시 줌)


<string name="access_token">(발급받은 접근 토큰 값)</string>


4. activity_main.xml (xml 구성)


<?xml version="1.0" encoding="utf-8"?>

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    // 꼭 필수로 적어줘야한다

    xmlns:mapbox="http://schemas.android.com/apk/res-auto"

    tools:context="com.example.a210.test.MainActivity">


    <com.mapbox.mapboxsdk.maps.MapView

        android:id="@+id/mapView"

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        mapbox:mapbox_styleUrl="@string/mapbox_style_light"

        mapbox:mapbox_cameraTilt="60"

        />

</android.support.constraint.ConstraintLayout>


※ styleUrl은 구글에 검색해서 자신이 원하는 스타일로 커스터마이징이 가능하다!!!


5. MainActivity.java


public class MainActivity extends AppCompatActivity {

    // private MapView mapView;

    private static final String TAG = "DirectionsActivity";

    private MapView mapView;

    private MapboxMap map;

    private DirectionsRoute currentRoute;

    private MapboxDirections client;

    double destinationX; // longitude

    double destinationY; // latitude


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        // 맵박스 사용하기 위한 접근 토큰 지정

        Mapbox.getInstance(this, getString(R.string.access_token));



        // 아래 함수로 통해 목적지 주소값을 위도 경도 값으로 변경

        getPointFromGeoCoder("서울특별시 송파구 방이동 112-1");


        // 내 gps 위치 (임의지정)

        final Point origin = Point.fromLngLat(126.867769, 37.500342);


        // 도착지 gps 위치

        final Point destination = Point.fromLngLat(destinationX, destinationY);



        // Setup the MapView

        mapView = findViewById(R.id.mapView);

        mapView.onCreate(savedInstanceState);

        mapView.getMapAsync(new OnMapReadyCallback() {

            @Override

            public void onMapReady(MapboxMap mapboxMap) {

                map = mapboxMap;


                // 카메라 위치 고정(내 gps 위치로 임의지정)

                map.animateCamera(CameraUpdateFactory.newLatLngZoom(

                        // 카메라는 반대의 값으로 적어줄 것

                        // 뒤에 숫자 15은 카메라 확대 배수이다( 15가 적당 )

                        new LatLng(37.500342, 126.867769), 15));


                // Add origin and destination to the map

                mapboxMap.addMarker(new MarkerOptions()

                        .position(new LatLng(origin.latitude(), origin.longitude()))

                        // 타이틀은 상호명 건물명, snippet은 설명 그에 대한 설명이다

                        // 출발지

                        .title("소우")

                        .snippet("소우2"));

                mapboxMap.addMarker(new MarkerOptions()

                        // 목적지

                        .position(new LatLng(destination.latitude(), destination.longitude()))

                        .title("가비")

                        .snippet("가비2"));


                // Get route from API

                getRoute(origin, destination);

            }

        });

    }


    private void getRoute(Point origin, Point destination) {


        client = MapboxDirections.builder()

                .origin(origin)

                .destination(destination)

                .overview(DirectionsCriteria.OVERVIEW_FULL)

                .profile(DirectionsCriteria.PROFILE_CYCLING)

                .accessToken(getString(R.string.access_token))

                .build();


        client.enqueueCall(new Callback<DirectionsResponse>() {

            @Override

            public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {

                System.out.println(call.request().url().toString());


                // You can get the generic HTTP info about the response

                Log.d(TAG, "Response code: " + response.code());

                if (response.body() == null) {

                    Log.e(TAG, "No routes found, make sure you set the right user and access token.");

                    return;

                } else if (response.body().routes().size() < 1) {

                    Log.e(TAG, "No routes found");

                    return;

                }


                // Print some info about the route

                currentRoute = response.body().routes().get(0);

                Log.d(TAG, "Distance: " + currentRoute.distance());


                // Draw the route on the map

                drawRoute(currentRoute);

            }


            @Override

            public void onFailure(Call<DirectionsResponse> call, Throwable throwable) {

                Log.e(TAG, "Error: " + throwable.getMessage());

                Toast.makeText(MainActivity.this, "Error: " + throwable.getMessage(), Toast.LENGTH_SHORT).show();

            }

        });

    }


    private void drawRoute(DirectionsRoute route) {

        // Convert LineString coordinates into LatLng[]

        LineString lineString = LineString.fromPolyline(route.geometry(), PRECISION_6);

        List<Point> coordinates = lineString.coordinates();

        LatLng[] points = new LatLng[coordinates.size()];

        for (int i = 0; i < coordinates.size(); i++) {

            points[i] = new LatLng(

                    coordinates.get(i).latitude(),

                    coordinates.get(i).longitude());

        }


        // Draw Points on MapView

        map.addPolyline(new PolylineOptions()

                .add(points)

                .color(Color.parseColor("#009688"))

                .width(5));

    }


    @Override

    public void onResume() {

        super.onResume();

        mapView.onResume();

    }


    @Override

    protected void onStart() {

        super.onStart();

        mapView.onStart();

    }


    @Override

    protected void onStop() {

        super.onStop();

        mapView.onStop();

    }


    @Override

    public void onPause() {

        super.onPause();

        mapView.onPause();

    }


    @Override

    protected void onSaveInstanceState(Bundle outState) {

        super.onSaveInstanceState(outState);

        mapView.onSaveInstanceState(outState);

    }


    @Override

    protected void onDestroy() {

        super.onDestroy();

        // Cancel the directions API request

        if (client != null) {

            client.cancelCall();

        }

        mapView.onDestroy();

    }


    @Override

    public void onLowMemory() {

        super.onLowMemory();

        mapView.onLowMemory();

    }


    // 목적지 주소값을 통해 목적지 위도 경도를 얻어오는 구문

    public void getPointFromGeoCoder(String addr) {

        String destinationAddr = addr;


        Geocoder geocoder = new Geocoder(this);

        List<Address> listAddress = null;

        try {

            listAddress = geocoder.getFromLocationName(destinationAddr, 1);

        } catch (IOException e) {

            e.printStackTrace();

        }


        destinationX = listAddress.get(0).getLongitude();

        destinationY = listAddress.get(0).getLatitude();


        System.out.println( addr + "'s Destination x, y = " + destinationX + ", " + destinationY);

    }

}






저작자표시 (새창열림)

'안드로이드' 카테고리의 다른 글

[안드로이드] - 생명주기에 맞게 개발하기  (0) 2018.06.14
[안드로이드] - WebView 를 이용해 사이트 가져오기  (0) 2018.06.01
[안드로이드] - 주소 값을 이용해 위도 경도 구하기  (0) 2018.05.31
[안드로이드] - 비동기 AsyncTask 예제 2개  (0) 2018.05.29
[안드로이드] - picasso로 이미지 URL 쉽게 ImageView에 띄워주기  (0) 2018.05.24

댓글()
카테고리
  • IT (593)
    • 정리 (0)
    • C# (42)
    • ASP.NET MVC (16)
    • JQuery&Javascript (12)
    • CSS (11)
    • 데이터베이스 (32)
    • Windows Server (6)
    • Active Directory (3)
    • Exchange (9)
    • JAVA (2)
    • JSP (39)
    • JSP 게시판 만들기 (21)
    • JSP 개발 참고 (15)
    • JSP 안드로이드 (4)
    • Servlet (17)
    • Spring (42)
    • HTML (14)
    • NodeJS (46)
    • MongoDB (11)
    • 리눅스 (18)
    • 자료구조 (16)
    • 아이폰 (24)
    • 안드로이드 (68)
    • API 활용하기 (10)
    • 소켓네트워크 (28)
    • 라즈베리파이 (11)
    • AWS클라우드 (10)
    • 빅데이터Hadoop (22)
    • 커널모듈프로그래밍 (8)
    • 기타 (10)
    • 자격증 (26)
최근 등록 현황
최근 글
최근 월별 글
최근 댓글
최근 글
최근 월별 글
최근 댓글
최근 글
최근 월별 글
최근 댓글
달력
지난달
2025.11
다음달
일월화수목금토
1
2345678
9101112131415
16171819202122
23242526272829
30
태그 구름
  • 정보처리산업기사 총정리
  • jsp
  • 정규화
  • 정보처리산업기사 필기 정리
  • 안드로이드
  • 정보처리산업기사 정리
  • HTML
  • 안드로이드 intent
  • 정보처리기사 실기 정리
  • 데이터베이스
  • 정보처리산업기사 요약
  • nodejs express
  • 정보처리산업기사 15년 필기
  • 카카오 로그인
  • 정규형
  • nodejs MySQL 연동하기(Connection Pool)
  • 소켓 프로그래밍
  • 커널 모듈 프로그래밍
  • 안드로이드 카카오 로그인
  • 안드로이드 카카오 로그인 연동
  • 이클립스 mysql 연동
  • 정보처리산업기사 15년
  • 정보처리산업기사 16년 필기
  • 카카오 로그인 연동
  • 자료구조
  • 정보처리산업기사 16년
  • 소켓
  • 이클립스 디비 연동
  • 정보처리산업기사 필기
  • 리눅스
카운터
전체 방문자
오늘
어제
Skin by M1REACT. Designed by M1STORY.TISTORY.COM. Valid XHTML 1.0 and CSS 3. Copyright ⓒ Riucc's Storage. All rights reserved.

티스토리툴바