이 페이지에서

지도 뷰어 (QML)

지도 뷰어 예제는 지도를 표시하고 상호 작용하는 방법, 주소를 검색하는 방법, 그리고 운전 경로를 찾는 방법을 보여줍니다.

“The Qt Company”라고 표시된 마커가 있는 오슬로 지도

이 예제는 Qt Location 에서 제공하는 지도, 위치 파악 및 내비게이션 서비스의 다양한 기본 사용법을 다루는 방대한 예제입니다. 이 페이지는 이러한 각 기능 영역을 다루는 섹션으로 나뉘어 있으며, 각 섹션에는 코드 스니펫이 포함되어 있습니다.

예제 실행

다음 위치에서 예제를 실행할 수 있습니다.

이 예제는 사용 가능한 모든 지리 서비스 플러그인과 함께 작동할 수 있습니다. 그러나 일부 플러그인의 경우 올바르게 작동하기 위해 추가적인 plugin parameters 가 필요할 수 있습니다. Plugin parameters 는 --plugin 인수를 사용하여 명령줄에서 전달할 수 있으며, 그 형식은 다음과 같습니다:

--plugin.<parameter name> <parameter value>

각 지리 서비스 플러그인이 지원하는 매개변수에 대한 자세한 내용은 해당 플러그인의 문서를 참조하십시오. 이 예제에서 사용되는 기본 플러그인은 Qt Location Open Street Map 플러그인이며, 이 플러그인은 별도의 매개변수가 필요하지 않습니다.

개요

이 예제에 표시된 QML 유형:

지도 표시하기

화면에 지도를 그리는 작업은 아래와 같이 ` MapView ` 타입을 사용하여 수행됩니다.

MapView {
    id: view
    map.zoomLevel: (maximumZoomLevel - minimumZoomLevel)/2
    map.center {
        // The Qt Company in Oslo
        latitude: 59.9485
        longitude: 10.7686
    }
}

MapView 은 map 을 기반으로 하며, 기본적인 내비게이션 기능을 확장합니다. 이 예제에서는 위도와 경도를 설정하여 지도 geoCoordinate 의 초기 중심을 지정합니다. 또한 초기 확대/축소 수준을 50%(최대값과 최소값의 중간)로 설정합니다.

주소 찾기(지오코딩)

지도에서 특정 주소나 장소를 찾는 데는 지오코딩(geocoding)이라는 과정이 사용됩니다. 지오코딩 작업을 수행하려면 먼저 결과를 수신할 수 있도록 Map 객체를 설정해야 합니다.

지오코딩 결과는 지오코딩 결과 처리기( GeocodeModel)를 통해 수신됩니다:

GeocodeModel {
    id: geocodeModel
    plugin: view.map.plugin
    onStatusChanged: {
        if ((status == GeocodeModel.Ready) || (status == GeocodeModel.Error))
            view.geocodeFinished()
    }
    onLocationsChanged:
    {
        if (count === 1) {
            view.map.center.latitude = get(0).coordinate.latitude
            view.map.center.longitude = get(0).coordinate.longitude
        }
    }
}

GeocodeModel 의 내용을 표시하기 위해 MapItemView 를 사용합니다:

MapItemView {
    parent: view.map
    model: geocodeModel
    delegate: pointDelegate
}

MapItemView delegate 는 생성되는 항목의 템플릿 역할을 하는 객체를 사용합니다. 여기에는 원하는 어떤 Map 객체라도 포함될 수 있지만, 이 예제에서는 마커 이미지를 포함하는 를 표시합니다: MapQuickItem

Component {
    id: pointDelegate

    MapQuickItem {
        id: point
        parent: view.map
        coordinate: locationData.coordinate

        sourceItem: Image {
            id: pointMarker
            source: "../resources/marker_blue.png"
        }
    }
}

이 세 가지 객체만 있으면 지오코드 응답을 수신하여 지도에 표시하는 데 충분합니다. 마지막으로 실제 지오코드 요청을 전송해야 합니다.

지오코드 요청을 보내려면 먼저 ` Address ` 객체를 생성하고, 원하는 매개변수를 입력합니다.

Address {
    id :fromAddress
    street: "Sandakerveien 116"
    city: "Oslo"
    country: "Norway"
    state : ""
    postalCode: "0484"
}

그런 다음 geocodeModel.query 객체를 매개변수가 설정된 Address 객체로 설정하고, GeocodeModel 객체에 대해 update() 메서드를 호출합니다.

// send the geocode request
geocodeModel.query = fromAddress
geocodeModel.update()

길찾기 및 이동 경로

GeocodeModel 와 마찬가지로, Qt Location 에도 RouteModel 유형이 포함되어 있어, 두 개 이상의 지점 간 경로(예: 운전 경로)에 대한 정보를 받아 Map 와 함께 사용할 수 있습니다.

여기서도 마찬가지로, RouteModel 를 Map의 속성으로 인스턴스화합니다:

RouteModel {
    id: routeModel
    plugin : view.map.plugin
    query:  RouteQuery {
        id: routeQuery
    }
    onStatusChanged: {
        if (status == RouteModel.Ready) {
            switch (count) {
            case 0:
                // technically not an error
                view.routeError()
                break
            case 1:
                view.showRouteList()
                break
            }
        } else if (status == RouteModel.Error) {
            view.routeError()
        }
    }
}

모델의 내용을 사용자에게 표시하려면 뷰가 필요합니다. 다시 한번 MapItemView 를 사용하여 지도 상에 경로(Routes)를 객체로 표시하겠습니다:

MapItemView {
    parent: view.map
    model: routeModel
    delegate: routeDelegate

뷰가 생성할 객체의 템플릿 역할을 하도록, 델리게이트 컴포넌트를 생성합니다:

Component {
    id: routeDelegate

    MapRoute {
        id: route
        route: routeData
        line.color: "#46a2da"
        line.width: 5
        smooth: true
        opacity: 0.8

이제 모델, 뷰, 델리게이트가 완성되었으므로, 남은 유일한 구성 요소는 경로 요청 프로세스를 시작하기 위해 모델을 제어할 수 있는 수단입니다. 가장 간단한 경우, 이미 사용 가능한 두 개의 coordinates 를 사용하여 경로 요청을 작성할 수 있습니다:

property variant fromCoordinate: QtPositioning.coordinate(59.9483, 10.7695)
property variant toCoordinate: QtPositioning.coordinate(59.9645, 10.671)

다음 코드 조각에서는 요청 객체를 설정하고 모델에 업데이트를 지시하는 방법을 보여줍니다. 또한 지도에 경로 요청의 시작 좌표를 중심으로 표시하도록 지시합니다.

// clear away any old data in the query
routeQuery.clearWaypoints();
// add the start and end coords as waypoints on the route
routeQuery.addWaypoint(startCoordinate)
routeQuery.addWaypoint(endCoordinate)
routeQuery.travelModes = RouteQuery.CarTravel
routeQuery.routeOptimizations = RouteQuery.FastestRoute
routeModel.update();
// center the map on the start coord
view.map.center = startCoordinate;

이것만으로도 지도에 경로를 표시하는 데 필요한 모든 작업이 완료됩니다. 하지만 작성된 길 안내와 이동 경로에 대한 설명을 가져올 수 있는 기능도 유용합니다. 이 예제에서는 이러한 내용이 ` ListView ` 요소에 표시됩니다. 이 콘텐츠를 생성하기 위해 표준 ` ListModel `과 ` ListView ` 쌍을 사용합니다. ` ListModel `의 데이터는 `routeModel`의 출력 결과를 바탕으로 구성됩니다:

ListView {
    interactive: true
    model: ListModel { id: routeInfoModel }
    header: RouteListHeader {}
    delegate:  RouteListDelegate{
        routeIndex.text: index + 1
        routeInstruction.text: instruction
        routeDistance.text: distance
    }
}

RouteModel 내부에서는, 위에서 볼 수 있듯이, onStatusChanged 핸들러를 추가합니다. 이 핸들러는 showRouteList() 를 호출하여 routeInfoModel 를 업데이트합니다:

routeInfoModel.clear()
if (routeModel.count > 0) {
    for (var i = 0; i < routeModel.get(0).segments.length; i++) {
        routeInfoModel.append({
            "instruction": routeModel.get(0).segments[i].maneuver.instructionText,
             "distance": Helper.formatDistance(routeModel.get(0).segments[i].maneuver.distanceToNextInstruction)
        });
    }
}

코드 예제 프로젝트 @ code.qt.io

© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.