선택
이 장은 지도에서 피처를 선택하는 방법을 설명합니다. 화면의 한 점(클릭)이나 지도 좌표의 다각형으로 선택하고, 적용 모드로 기존 선택과 합치고, 선택을 바꾸지 않고 질의하고, 선택을 읽고, 바뀔 때 알림을 받는 순서입니다. 아무것도 맞지 않을 때와 선택할 수 없는 레이어의 동작, 선택과 히트 테스트의 차이, 실패의 형태도 다룹니다.
이 장의 코드는 sdk_samples의 selection 예제에서 가져왔습니다. 실행할 때는 데이터 폴더를 첫 인자로 줍니다(<실행 파일> <sdk_samples/data 폴더>). 예제는 파일을 쓰지 않습니다. 예제 데이터 harbor_town.gpkg는 읽기 전용으로 열고, 스타일 파일은 데이터 폴더의 styles 폴더에서 읽기만 합니다. 이 장은 시작하기의 호환성 확인과 공급자 등록이 끝났다고 가정합니다(초기화와 종료).
지도 뷰와 피처 레이어를 직접 만드는 방법은 8장 레이어와 스타일에서, 지도 좌표와 화면 좌표의 변환은 7장에서 설명했습니다.
선택 서비스
선택은 레이어에 있습니다. 피처 레이어마다 선택된 피처의 id 목록을 가집니다(glsFeatureLayer의 GetSelectedIds, SetSelectedIds). 선택 서비스 glsSelectionService는 지도 뷰의 피처 레이어에서 이 목록을 읽고 쓰는 창구입니다. 서비스는 관찰자와 필터 말고는 상태를 따로 갖지 않고 호출할 때마다 레이어의 목록을 다시 읽으므로, 한 지도 뷰에 서비스를 여러 개 만들어도 서로 어긋나지 않습니다. 서비스는 스레드 안전하지 않습니다.
서비스가 하는 일은 다음과 같습니다.
- 레이어 id로 선택을 읽고 쓰기(
GetSelectedIds,SetSelectedIds,AddSelectedIds,ToggleSelectedIds,ClearSelection등). id로 찾을 때는 그룹 안의 레이어도 찾습니다. - 화면의 점이나 지도 좌표의 다각형으로 피처를 찾아 선택하기(
ExecuteAtScreenPoint,Execute)와, 선택하지 않고 찾기만 하기(Query). - 선택된 피처의 범위(
GetSelectionExtent)와 모든 레이어의 선택 지우기(ClearAll). - 서비스를 거친 쓰기를 알리기(변경 알림).
선택 가능 여부. 레이어의 선택 가능 여부(C++ GetSelectable/SetSelectable, C# Selectable)는 레이어를 만드는 호출이 따로 정하지 않으면 false로 시작합니다. 8장처럼 피처 레이어를 직접 만들 때(C++ glsCreateFeatureLayer, C# new glsFeatureLayer)와 워크스페이스가 데이터셋을 더하며 만드는 기본 레이어가 그렇습니다. 워크스페이스 파일에서 연 레이어는 파일에 저장된 값을 가집니다. 화면이나 다각형으로 선택하려면 선택 가능 여부가 true인지 확인하세요. 히트맵으로 그리는 피처 레이어는 이 값과 관계없이 선택할 수 없습니다. 레이어 id로 읽고 쓰는 호출은 선택 가능 여부를 보지 않습니다.
id. 선택 목록의 값은 레이어가 읽는 데이터 소스의 피처 id(FID)입니다. 편집 중인 레이어에서는 이 id의 뜻이 달라지며, 그 내용은 10장 편집에서 다룹니다.
예제는 8장과 같은 방법으로 districts, roads, places 순서로 레이어를 만들어 더하고(그래서 places가 맨 위입니다), 세 레이어를 선택 가능하게 바꾼 뒤 640x480으로 크기를 정하고 구역 전체로 맞춥니다. 레이어를 더하는 부분은 공용 도우미 AddHarborLayers(C++ common/sample_map.h, C# Common\SampleMap.cs)에 있습니다.
선택 서비스의 헤더 gdk_dll/selection/glsSelectionService.h는 gdk_dll/glsGDK.h에 들어 있지 않으므로 따로 포함합니다. glsSelectionService(glsMapView*)는 지도 뷰를 빌립니다. 서비스를 쓰는 동안 지도 뷰가 살아 있어야 하며, 예제처럼 서비스를 지도 뷰보다 먼저 없애세요. 서비스는 보통 객체로 만들고 반납 함수가 없습니다.
// Builds the map the selection works on. New layers are not selectable, so
// every layer is made selectable first. The view gets its size and extent
// before any screen point is computed.
static bool prepareMap(GDK::glsDataset& dataset, GDK::glsMapView& view, const std::filesystem::path& dataDir)
{
if (!sample::addHarborLayers(dataset, view, (dataDir / "styles").u8string())) {
return false; // addHarborLayers has printed why
}
const char* const ids[] = {"districts", "roads", "places"};
for (const char* id : ids) {
LayerPtr layer = layerById(view, id);
bool before = true;
if (!layer || !succeeded(layer->GetSelectable(&before)) || !succeeded(layer->SetSelectable(true))) {
return false;
}
std::printf("[sample] %s: selectable %s -> true\n", id, yesNo(before));
if (before) {
return unexpected("expected a new layer not to be selectable");
}
}
if (!succeeded(view.Resize(kWidth, kHeight, kDpi, kDpi)) || !succeeded(view.ZoomToLayer("districts", 0.05))) {
return false;
}
return sample::waitForFrame(view, kRenderTimeoutMs); // waitForFrame prints why it failed
}
후보 레이어와 순서
화면이나 다각형으로 선택할 때(ExecuteAtScreenPoint, Execute, Query) 다음을 모두 만족하는 피처 레이어가 후보입니다.
- 보입니다. 레이어 자신과 그 레이어를 품은 모든 그룹이 보여야 합니다.
- 선택 가능합니다. 레이어 자신의 값만 봅니다. 그룹의 선택 가능 여부는 상관없습니다.
- 지금 축척에서 그려집니다. 레이어 자신과 품은 모든 그룹의 축척 범위 안이어야 합니다(공통 속성).
- id가 비어 있지 않습니다.
후보는 위에서부터, 곧 그려지는 순서의 반대로 훑습니다. 맨 위 수준의 순서 값이 큰 레이어(그룹)가 먼저이고, 순서 값이 같으면 나중에 그려지는 쪽이 먼저이며, 그룹 안에서는 목록의 마지막 자식이 먼저입니다(순서).
서비스는 위의 후보부터 하나씩 질의하다가 맞은 피처가 있는 첫 레이어에서 멈춥니다. 그 레이어가 대상이 되고, 결과는 언제나 그 한 레이어입니다. 대상보다 아래의 레이어는 열지도 질의하지도 않습니다. 대상보다 위에서 질의한 레이어에서 오류가 나면 아무것도 쓰기 전에 호출 전체가 실패합니다.
C++에서는 SetLayerFilter(IGlsSelectionLayerFilter)로 후보를 더 줄이고, SetFeatureFilter(IGlsSelectionFeatureFilter)로 후보 피처를 뺄 수 있습니다. 둘 다 빌린 객체이며 nullptr로 해제합니다. C#에는 레이어 필터만 있고, ExecuteAtScreenPoint의 Func<string, bool>을 받는 오버로드로 그 호출에만 씁니다.
후보가 하나도 없는 경우는 실패입니다. 후보가 있는데 맞은 것이 없는 경우는 실패가 아닙니다(맞은 것이 없을 때).
점으로 선택
ExecuteAtScreenPoint(x, y, radiusPixels, request)는 화면 점 둘레의 정사각형(가로세로 각각 ±반지름, 반지름은 1보다 작으면 1)을 선택 영역으로 삼습니다. 화면 좌표와 반지름은 기기 픽셀입니다. 정사각형의 네 모서리를 ScreenToWorld로 지도 좌표로 바꾼 뒤 다각형으로 선택과 같은 규칙으로 처리하므로, 지도 뷰의 크기와 범위가 정해진 뒤에 부르세요.
요청의 SingleHit을 켜면 클릭 선택이 됩니다. 대상 레이어에서 맞은 피처 가운데 하나만 골라 적용하고, 고른 id는 결과의 PrimaryFeatureId에 들어 있습니다(그 밖의 경우 -1). 고르는 규칙은 다음과 같습니다.
- 맞은 피처 가운데 아직 선택되지 않은 첫 피처를 고릅니다.
PreferAfterCurrent를 켜면, 맞은 피처 가운데 지금 선택된 것이 있을 때 그다음(끝에서는 처음으로 돌아가) 선택되지 않은 피처를 고릅니다. 겹친 피처를 클릭할 때마다 차례로 바꿔 고를 때 씁니다.- 맞은 피처가 모두 이미 선택되어 있으면 적용 모드가
Toggle일 때만 그중 하나를 골라 선택을 풉니다. 그 밖의 모드에서는 아무것도 고르지 않으며, 호출은 성공하고 결과의Applied가false이고 선택은 그대로입니다.
예제는 Spice Market의 지도 좌표를 WorldToScreen으로 화면 점으로 바꿔 반지름 3픽셀로 클릭합니다. 맨 위 레이어 places가 맞으므로 피처 하나(id 5)가 선택됩니다.
요청은 glsSelectionRequest 구조체, 결과는 호출자가 만드는 glsSelectionResult 객체입니다. 결과를 받는 호출은 먼저 결과를 비웁니다. 결과의 레이어 id는 두 번 호출하는 방식으로 읽습니다.
// A click selects at a screen point: the square of +-radius pixels around it is
// the selection area. SingleHit picks one feature of the topmost layer that has
// a hit. The screen point comes from the map point of Spice Market.
static bool selectAtPoint(GDK::glsSelectionService& selection, const GDK::glsMapView& view)
{
GDK::glsSelectionResult result;
if (!clickAt(selection, view, kSpiceMarket, true, result)) {
return false;
}
const std::string layer = resultLayerId(result);
std::printf("[sample] click on Spice Market: layer %s, feature %" PRId64 ", %d selected\n", layer.c_str(),
result.GetPrimaryFeatureId(), result.GetSelectedCount());
return (layer == "places" && result.GetPrimaryFeatureId() == 5 && result.GetApplied() &&
result.GetSelectedCount() == 1) ||
unexpected("expected one place");
}
다각형으로 선택
Execute(mapPoints, request)는 지도 좌표의 꼭짓점 목록을 링으로 받아 그 다각형으로 선택합니다. 꼭짓점은 3개 이상이어야 하며 링은 자동으로 닫힙니다. 사각형은 네 모서리를, 원은 둘레의 점 여러 개를 주면 됩니다. 링은 레이어마다 그 데이터 소스의 좌표계로 바뀐 뒤 질의에 쓰입니다. 다만 지도나 레이어의 좌표계가 없거나 읽을 수 없거나 올바르지 않으면 링을 바꾸지 않고 지도 좌표 그대로 질의하며, 결과에 경고(Warning)를 남깁니다(선택을 바꾸지 않는 질의의 결과 표).
요청의 필드와 기본값은 다음과 같습니다.
| 필드 | 기본값 | 뜻 |
|---|---|---|
Mode |
Replace |
맞은 피처를 기존 선택과 합치는 방법(적용 모드) |
Operation |
Intersects |
Intersects는 영역과 닿는 피처, Contains는 영역 안에 완전히 들어가는 피처를 맞힙니다. |
SingleHit |
끔 | 맞은 피처 하나만 적용합니다(점으로 선택). |
PreferAfterCurrent |
끔 | SingleHit일 때 지금 선택의 다음 피처를 고릅니다. |
예제는 Old Harbor 구역 안의 사각형으로 선택합니다. 사각형은 도로와 구역에도 닿지만 맨 위 레이어 places에 맞은 피처(Lighthouse Pier, Fish Dock)가 있으므로 places의 두 피처가 선택됩니다.
Execute(const glsMapPoint*, int, const glsSelectionRequest&, glsSelectionResult*)의 결과 인자는 nullptr이어도 됩니다.
// An area selection takes a ring in map coordinates (three points or more; it
// is closed automatically). Every feature of the topmost layer with a hit is
// matched; the layers below are not used. The rectangle lies inside Old
// Harbor and crosses roads, but places is on top and has two hits.
static bool selectInRect(GDK::glsSelectionService& selection)
{
const std::vector<GDK::glsMapPoint> points = ring(kOldHarborRect);
GDK::glsSelectionRequest request; // Replace, Intersects
GDK::glsSelectionResult result;
if (!succeeded(selection.Execute(points.data(), static_cast<int>(points.size()), request, &result))) {
return false;
}
const std::string layer = resultLayerId(result);
std::printf("[sample] rectangle in Old Harbor: layer %s, %d matched, %d selected\n", layer.c_str(),
result.GetMatchedCount(), result.GetSelectedCount());
return (layer == "places" && result.GetMatchedCount() == 2 && result.GetSelectedCount() == 2) ||
unexpected("expected two places");
}
적용 모드
대상 레이어가 정해지고 적용할 피처가 있으면, 서비스는 다른 모든 피처 레이어(id가 빈 레이어는 빼고)의 선택을 먼저 지우고 대상 레이어에 적용 모드를 적용합니다. 그래서 선택을 쓴 호출(결과의 Applied가 true)의 뒤에는 선택이 한 레이어에만 있습니다. 지우는 레이어는 보이기나 선택 가능 여부와 관계없습니다. SingleHit에서 고를 피처가 없으면(점으로 선택) 아무것도 지우거나 쓰지 않으므로 다른 레이어의 선택도 그대로입니다.
| 모드 | 대상 레이어의 새 선택 |
|---|---|
Replace |
맞은 피처 |
Add |
지금 선택에 아직 없는 맞은 피처를 뒤에 덧붙임 |
Toggle |
맞은 피처 가운데 선택된 것은 빼고, 선택되지 않은 것은 덧붙임 |
레이어 id로 쓰는 호출(SetSelectedIds, AddSelectedIds, ToggleSelectedIds)도 같은 규칙으로 목록을 만들고, 겹치는 id는 처음 나온 순서로 하나만 남깁니다. 다만 이 호출들은 그 레이어만 바꾸고 다른 레이어의 선택은 건드리지 않으므로, 여러 레이어에 선택이 남을 수 있습니다.
예제는 Old Harbor 사각형으로 고른 두 장소에서 시작해, Market Quarter 사각형을 Add로 더해 4건, Fish Dock만 덮는 사각형을 Toggle로 적용해 3건, Market Quarter 사각형을 Replace로 적용해 2건(Central Market, Spice Market)을 만듭니다.
// The mode says how the hits combine with the layer's current selection:
// Replace sets them, Add appends the ones not yet selected, and Toggle removes
// the selected ones and adds the others.
static bool applyModes(GDK::glsSelectionService& selection)
{
struct Step {
const char* label;
GDK::glsSelectionApplyMode mode;
Rect rect;
int expected;
};
const Step steps[] = {
{"Add Market Quarter rectangle", GDK::glsSelectionApplyMode::Add, kMarketRect, 4},
{"Toggle Fish Dock rectangle", GDK::glsSelectionApplyMode::Toggle, kFishDockRect, 3},
{"Replace with Market Quarter rectangle", GDK::glsSelectionApplyMode::Replace, kMarketRect, 2},
};
for (const Step& step : steps) {
const std::vector<GDK::glsMapPoint> points = ring(step.rect);
GDK::glsSelectionRequest request;
request.Mode = step.mode;
GDK::glsSelectionResult result;
if (!succeeded(selection.Execute(points.data(), static_cast<int>(points.size()), request, &result))) {
return false;
}
std::printf("[sample] %s: %d selected\n", step.label, result.GetSelectedCount());
if (result.GetSelectedCount() != step.expected) {
return unexpected(step.label);
}
}
return true;
}
선택을 바꾸지 않는 질의
Query(mapPoints, operation)는 Execute와 같은 후보, 같은 순서, 같은 대상 규칙으로 맞은 피처를 찾지만 아무것도 쓰지 않고 알리지도 않습니다. 결과에는 대상 레이어 id와 맞은 id 목록이 들어 있으며, 대상이 없으면 레이어 id가 빈 문자열이고 맞은 수가 0입니다.
결과의 값은 다음과 같습니다.
| 값 | 뜻 |
|---|---|
| 레이어 id | 대상 레이어. 맞은 것이 없으면 빈 문자열 |
| 맞은 id | 대상 레이어에서 맞은 피처의 id |
Applied |
선택을 썼는지. Query는 언제나 false |
SelectedCount |
적용한 뒤 대상 레이어의 선택 수. 쓰지 않았거나 대상이 없으면 0 |
PrimaryFeatureId |
SingleHit으로 고른 id, 그 밖에는 -1 |
Warning |
glsSelectionWarning. 지도나 레이어의 좌표계를 확인하지 못했거나 좌표계가 올바르지 않아 좌표를 바꾸지 않고 계속했으면 None이 아닌 값입니다. 실패가 아닙니다. |
예제는 Old Harbor 사각형을 질의해 places의 2건이 맞지만 선택(2건)이 그대로임을 확인합니다. 이어서 Quay Road의 북쪽 끝에 걸친 사각형을 질의합니다. 이 사각형에는 장소가 없고 도로 하나의 일부가 들어 있습니다. Intersects로는 roads의 1건이 맞고, Contains로는 도로가 사각형 안에 다 들어가지 않으므로 roads에서 맞지 않고, 그 아래 districts의 구역도 사각형 안에 들어가지 않으므로 대상이 없습니다.
Query(const glsMapPoint*, int, glsSelectionSpatialOperation, glsSelectionResult*)의 결과 인자는 꼭 있어야 합니다. 결과의 개수는 GetMatchedCount, id는 GetMatchedIds로 읽습니다.
// Query finds the same target layer and hits as Execute but writes nothing.
// Intersects matches a feature that touches the area; Contains only a feature
// that lies completely inside it.
static bool queryOnly(GDK::glsSelectionService& selection)
{
const std::vector<GDK::glsMapPoint> harbor = ring(kOldHarborRect);
GDK::glsSelectionResult result;
if (!succeeded(selection.Query(harbor.data(), static_cast<int>(harbor.size()),
GDK::glsSelectionSpatialOperation::Intersects, &result))) {
return false;
}
const int stillSelected = selectedCount(selection, "places");
if (stillSelected < 0) {
return false; // selectedCount has printed why
}
const std::string harborLayer = resultLayerId(result);
std::printf("[sample] query in Old Harbor: layer %s, %d matched; places still has %d selected\n",
harborLayer.c_str(), result.GetMatchedCount(), stillSelected);
if (harborLayer != "places" || result.GetMatchedCount() != 2 || stillSelected != 2) {
return unexpected("the query changed the selection");
}
const std::vector<GDK::glsMapPoint> quay = ring(kQuayRoadRect);
const GDK::glsSelectionSpatialOperation operations[] = {GDK::glsSelectionSpatialOperation::Intersects,
GDK::glsSelectionSpatialOperation::Contains};
const char* const names[] = {"Intersects", "Contains"};
const int expected[] = {1, 0};
const char* const expectedLayers[] = {"roads", ""};
for (int i = 0; i < 2; ++i) {
if (!succeeded(selection.Query(quay.data(), static_cast<int>(quay.size()), operations[i], &result))) {
return false;
}
const std::string layer = resultLayerId(result);
std::printf("[sample] %s across Quay Road: layer \"%s\", %d matched\n", names[i], layer.c_str(),
result.GetMatchedCount());
if (layer != expectedLayers[i] || result.GetMatchedCount() != expected[i]) {
return unexpected(names[i]);
}
}
return true;
}
선택 읽기
- 레이어별 id와 수.
GetSelectedIds(layerId),GetSelectedCount(layerId). 레이어가 없으면 실패합니다. 레이어의 보이기나 선택 가능 여부는 보지 않습니다. - 선택이 있는 레이어.
GetSelectedLayerId()는 선택된 피처가 있는 피처 레이어 가운데 그리는 순서로 맨 위의 것을 돌려줍니다. 이때는 보이기, 선택 가능 여부, 축척을 보지 않습니다. 점이나 다각형으로 선택을 쓴 뒤에는 선택이 한 레이어에만 있으므로(적용 모드) 그 레이어가 돌아옵니다. 아무 레이어에도 선택이 없으면 C++은NotFound(오류 종류NoSelectedFeatures)로 실패하고, C#은null을 돌려줍니다. - 피처. 선택은 id만 담습니다. 속성이나 지오메트리가 필요하면 레이어의 데이터 소스에서 id로 읽습니다(피처 읽기와 질의).
- 범위.
GetSelectionExtent는 선택이 있는 모든 피처 레이어(보이기와 선택 가능 여부와 관계없이)의 선택된 피처 범위를 지도 좌표로 합친 것과, 선택된 피처의 전체 수를 돌려줍니다. 각 레이어의 피처를 데이터 소스에서 읽어 계산합니다. 선택이 없으면NotFound(NoSelectedFeatures)로 실패합니다.
예제는 선택이 있는 레이어(places)와 id(4, 5)를 읽고, 데이터 소스에서 두 피처의 이름을 읽은 뒤 범위 10.040 50.010 10.050 50.020을 출력합니다.
C++에는 보이고 선택 가능한 피처 레이어만 세는 호출도 있습니다. GetSelectedFeatures(레이어 id와 피처 id의 쌍 목록, glsSelectedFeatureList), GetTotalSelectedCount, HasAnySelection입니다. 앞의 두 호출은 보이고 선택 가능한 레이어 가운데 id가 빈 레이어가 있으면 실패합니다.
// The selection is stored on each feature layer as feature ids. The ids are
// read here and the features are read from the layer's data source.
// GetSelectionExtent is the extent of the selected features in map
// coordinates.
static bool readSelection(GDK::glsSelectionService& selection, const GDK::glsMapView& view)
{
const std::string layerId = selectedLayerId(selection);
if (layerId.empty()) {
return false;
}
std::vector<int64_t> ids;
if (layerId != "(none)") {
int required = 0;
if (!succeeded(selection.GetSelectedIds(layerId.c_str(), nullptr, 0, &required))) {
return false;
}
ids.resize(static_cast<size_t>(required));
if (required > 0 &&
!succeeded(selection.GetSelectedIds(layerId.c_str(), ids.data(), required, &required))) {
return false;
}
}
std::string text;
for (int64_t id : ids) {
text += " " + std::to_string(id);
}
std::printf("[sample] selected layer: %s, ids:%s\n", layerId.c_str(), text.c_str());
LayerPtr layer = layerById(view, layerId.c_str());
auto* feature = dynamic_cast<GDK::glsFeatureLayer*>(layer.get());
GDK::glsDataSource* rawSource = nullptr;
if (feature == nullptr || !succeeded(feature->GetDataSource(&rawSource))) {
return false;
}
DataSourcePtr source(rawSource);
GDK::glsFeatureDefn* rawDefn = nullptr;
if (!succeeded(source->GetFeatureDefn(&rawDefn))) {
return false;
}
DefnPtr defn(rawDefn, GDK::glsReleaseFeatureDefn);
int nameIndex = -1;
if (!succeeded(defn->GetFieldIndex("name", &nameIndex))) {
return false;
}
std::vector<std::string> names;
for (int64_t id : ids) {
GDK::glsFeature row;
bool found = false;
GDK::glsAttributeValue value;
if (!succeeded(source->GetFeatureById(id, &row, &found))) {
return false;
}
if (!found) {
return unexpected("a selected feature was not found");
}
if (!succeeded(row.GetAttribute(nameIndex, &value))) {
return false;
}
const char* name = value.Type == GDK::glsAttributeValueType::String && value.StringValue ? value.StringValue
: "";
std::printf("[sample] feature %" PRId64 ": %s\n", id, name);
names.push_back(name);
}
GDK::glsEnvelope e;
int count = 0;
if (!succeeded(selection.GetSelectionExtent(&e, &count))) {
return false;
}
std::printf("[sample] selection extent %.3f %.3f %.3f %.3f, %d selected\n", e.MinX, e.MinY, e.MaxX, e.MaxY,
count);
// C++ only: the count over the visible, selectable feature layers.
int total = 0;
bool any = false;
if (!succeeded(selection.GetTotalSelectedCount(&total)) || !succeeded(selection.HasAnySelection(&any))) {
return false;
}
std::printf("[sample] total selected: %d, any selection: %s\n", total, yesNo(any));
// Central Market (10.04 50.01) and Spice Market (10.05 50.02).
const bool extentOk = std::fabs(e.MinX - 10.04) < 1e-6 && std::fabs(e.MinY - 50.01) < 1e-6 &&
std::fabs(e.MaxX - 10.05) < 1e-6 && std::fabs(e.MaxY - 50.02) < 1e-6;
return (layerId == "places" && ids.size() == 2 && ids[0] == 4 && ids[1] == 5 && names[0] == "Central Market" &&
names[1] == "Spice Market" && extentOk && count == 2 && total == 2 && any) ||
unexpected("expected two places");
}
변경 알림
서비스는 자기를 거친 쓰기를 알립니다. 알림은 쓰기가 끝난 직후, 호출한 스레드에서, 호출이 돌아오기 전에 동기로 옵니다. 알림에는 레이어 id와 쓴 뒤 그 레이어의 선택 수가 들어 있습니다.
- 레이어 id로 쓰는 호출(
SetSelectedIds,AddSelectedIds,ToggleSelectedIds,ClearSelection)은 쓸 때마다 한 번 알립니다. 선택이 그대로여도 알립니다. - 점이나 다각형으로 선택하면 선택을 지운 다른 레이어마다 한 번씩(수 0) 알린 뒤 대상 레이어를 알립니다. 그래서 한 호출이 여러 번 알릴 수 있습니다. 앞의 레이어를 지운 뒤 나중 단계가 실패해도 이미 보낸 알림은 그대로입니다.
ClearAll은 선택이 있던 레이어만 지우고 그 레이어마다 알립니다.glsFeatureLayer의SetSelectedIds등으로 레이어에 직접 쓰면 알리지 않습니다. 다른 서비스 객체를 거친 쓰기도 이 서비스는 알리지 않습니다.
예제는 알림을 건 뒤 districts에 id로 선택을 쓰고(1번), 그 상태에서 두 레이어에 선택이 있을 때 GetSelectedLayerId가 맨 위의 places를 돌려주는 것을 봅니다. 이어서 Old Harbor 사각형으로 선택하면 districts를 지운 알림과 places의 알림이 옵니다(2번). 마지막으로 places 레이어에 직접 쓰면 알림이 없어 모두 3번입니다.
IGlsSelectionObserver를 구현해 SetObserver로 겁니다. 서비스 하나에 관찰자는 하나이고, 서비스는 관찰자를 빌리므로 관찰자를 없애기 전에 SetObserver(nullptr)로 풉니다. OnSelectionChanged는 noexcept이며 예외가 빠져나가면 안 됩니다.
// The observer is told about every write made through this service object,
// synchronously, on the calling thread, after the write. An area or click
// selection that hits one layer clears the other layers first, so it can
// notify more than once. A write made directly on a layer notifies nobody.
static bool selectionObserver(GDK::glsSelectionService& selection, const GDK::glsMapView& view)
{
struct PrintingObserver final : GDK::IGlsSelectionObserver {
int calls = 0;
void OnSelectionChanged(const char* layerId, int selectedCount) noexcept override
{
++calls;
std::printf("[sample] notified: %s has %d selected\n", layerId, selectedCount);
}
} observer;
selection.SetObserver(&observer);
bool ok = false;
do {
// Writing by id may leave two layers with a selection; the topmost one is reported.
const int64_t marketQuarter[] = {2};
if (!succeeded(selection.SetSelectedIds("districts", marketQuarter, 1))) {
break;
}
const std::string topmost = selectedLayerId(selection);
if (topmost.empty()) {
break; // selectedLayerId has printed why
}
std::printf("[sample] two layers have a selection, topmost: %s\n", topmost.c_str());
const std::vector<GDK::glsMapPoint> points = ring(kOldHarborRect);
GDK::glsSelectionRequest request;
if (!succeeded(selection.Execute(points.data(), static_cast<int>(points.size()), request, nullptr))) {
break;
}
LayerPtr layer = layerById(view, "places");
auto* places = dynamic_cast<GDK::glsFeatureLayer*>(layer.get());
const int64_t lighthousePier[] = {1};
if (places == nullptr || !succeeded(places->SetSelectedIds(lighthousePier, 1))) {
break;
}
const int placesCount = selectedCount(selection, "places");
if (placesCount < 0) {
break; // selectedCount has printed why
}
std::printf("[sample] notifications: %d, places now has %d selected\n", observer.calls, placesCount);
ok = (topmost == "places" && observer.calls == 3 && placesCount == 1) ||
unexpected("expected three notifications");
} while (false);
selection.SetObserver(nullptr); // the service only borrows the observer
return ok;
}
맞은 것이 없을 때와 선택할 수 없는 레이어
후보가 아닌 레이어는 없는 것과 같습니다. 레이어를 숨기거나, 지금 축척을 레이어의 축척 범위 밖으로 두거나, 선택 불가로 바꾸면 그 레이어는 후보에서 빠지고 그 아래의 후보가 대상이 될 수 있습니다. 예제는 Spice Market 위의 작은 정사각형으로 (SingleHit 없이) 선택하는데, places를 숨겼을 때, 축척 범위 밖으로 두었을 때, 선택 불가로 바꾸었을 때 모두 그 아래 districts의 구역(Market Quarter)이 선택됩니다. 이때 다른 레이어의 선택을 지우는 규칙에 따라 places의 선택도 지워집니다.
후보가 하나도 없으면 실패합니다. 결과 코드는 NotFound, 오류 종류는 NoVisibleSelectableLayers이고, 아무것도 쓰지 않으므로 기존 선택은 그대로입니다. 예제는 세 레이어를 모두 선택 불가로 바꿔 이것을 확인합니다.
후보는 있지만 맞은 것이 없으면 실패가 아닙니다. 결과의 레이어 id가 빈 문자열이고, 기존 선택은 요청에 따라 다음과 같습니다.
| 요청 | 결과 |
|---|---|
SingleHit (모드와 관계없이) |
아무것도 쓰지 않음, Applied = false |
영역 선택, Add 또는 Toggle |
아무것도 쓰지 않음, Applied = false |
영역 선택, Replace |
모든 레이어의 선택을 지움, Applied = true |
예제는 Garden Quarter 구역의 구멍 한가운데(어떤 피처도 덮지 않는 곳)에서 세 경우를 차례로 확인합니다. 클릭과 Add는 districts의 선택을 남기고, Replace는 모든 선택을 지웁니다.
// Only layers that are visible (with every group above them), selectable and
// drawn at the current scale are candidates. A click on Spice Market hits
// districts when places is not a candidate. When no layer is a candidate the
// call fails and the selection stays as it was.
static bool notSelectable(GDK::glsSelectionService& selection, GDK::glsMapView& view)
{
LayerPtr layer = layerById(view, "places");
if (!layer) {
return false;
}
double scale = 0;
if (!succeeded(view.GetScaleDenominator(&scale))) {
return false;
}
const char* const cases[] = {"hidden", "out of its scale range", "not selectable"};
for (int i = 0; i < 3; ++i) {
GDK::glsStatus status = i == 0 ? layer->SetVisible(false)
: i == 1 ? layer->SetScaleRange(0, scale / 2)
: layer->SetSelectable(false);
GDK::glsSelectionResult result;
if (!succeeded(status) || !clickAt(selection, view, kSpiceMarket, false, result)) {
return false;
}
const std::string target = resultLayerId(result);
const int placesCount = selectedCount(selection, "places");
if (placesCount < 0) {
return false; // selectedCount has printed why
}
std::printf("[sample] places %s: selection at Spice Market goes to %s (%d selected); places has %d selected\n",
cases[i], target.c_str(), result.GetSelectedCount(), placesCount);
if (target != "districts" || result.GetSelectedCount() != 1 || placesCount != 0) {
return unexpected("expected districts");
}
status = i == 0 ? layer->SetVisible(true) : i == 1 ? layer->SetScaleRange(0, 0) : layer->SetSelectable(true);
if (!succeeded(status)) {
return false;
}
}
const char* const ids[] = {"districts", "roads", "places"};
for (const char* id : ids) {
LayerPtr each = layerById(view, id);
if (!each || !succeeded(each->SetSelectable(false))) {
return false;
}
}
bool selectable = true;
if (!succeeded(selection.IsLayerSelectable("places", &selectable))) {
return false;
}
GDK::glsScreenPoint screen;
if (!toScreen(view, kSpiceMarket, screen)) {
return false;
}
GDK::glsSelectionRequest request;
GDK::glsSelectionResult result;
const GDK::glsStatus status = selection.ExecuteAtScreenPoint(screen.X, screen.Y, kClickRadius, request, &result);
const GDK::glsErrorDetail detail = GDK::glsGetLastErrorDetail(); // read right after the failed call
const bool expectedFailure = status.Code == GDK::glsResultCode::NotFound &&
detail.Domain == GDK::glsErrorDomain::Selection &&
detail.Kind == static_cast<int32_t>(GDK::glsSelectionErrorKind::NoVisibleSelectableLayers);
std::printf("[sample] no selectable layer (places selectable: %s): %s\n", yesNo(selectable),
expectedFailure ? "NotFound, NoVisibleSelectableLayers" : "unexpected");
const int kept = selectedCount(selection, "districts");
if (kept < 0) {
return false; // selectedCount has printed why
}
std::printf("[sample] districts still has %d selected\n", kept);
for (const char* id : ids) {
LayerPtr each = layerById(view, id);
if (!each || !succeeded(each->SetSelectable(true))) {
return false;
}
}
return (expectedFailure && !selectable && kept == 1) ||
unexpected("expected the call to fail and keep the selection");
}
// Nothing lies in the hole of Garden Quarter. A click there (SingleHit) and an
// Add or Toggle area selection change nothing; a Replace area selection clears
// every layer. None of them fails.
static bool noHit(GDK::glsSelectionService& selection, const GDK::glsMapView& view)
{
GDK::glsSelectionResult result;
if (!clickAt(selection, view, kEmptySpot, true, result)) {
return false;
}
const std::string clickLayer = resultLayerId(result);
const int districts = selectedCount(selection, "districts");
if (districts < 0) {
return false; // selectedCount has printed why
}
std::printf("[sample] click on an empty spot: applied %s, layer \"%s\", districts has %d selected\n",
yesNo(result.GetApplied()), clickLayer.c_str(), districts);
if (result.GetApplied() || !clickLayer.empty() || districts != 1) {
return unexpected("expected the click to change nothing");
}
GDK::glsScreenPoint screen;
if (!toScreen(view, kEmptySpot, screen)) {
return false;
}
const GDK::glsSelectionApplyMode modes[] = {GDK::glsSelectionApplyMode::Add,
GDK::glsSelectionApplyMode::Replace};
const char* const names[] = {"Add", "Replace"};
const bool expectedApplied[] = {false, true};
const char* const expectedLayers[] = {"districts", "(none)"};
for (int i = 0; i < 2; ++i) {
GDK::glsSelectionRequest area; // not SingleHit: an area selection
area.Mode = modes[i];
if (!succeeded(selection.ExecuteAtScreenPoint(screen.X, screen.Y, kClickRadius, area, &result))) {
return false;
}
const std::string selected = selectedLayerId(selection);
if (selected.empty()) {
return false; // selectedLayerId has printed why
}
std::printf("[sample] %s on an empty spot: applied %s, layer \"%s\", selected layer %s\n", names[i],
yesNo(result.GetApplied()), resultLayerId(result).c_str(), selected.c_str());
if (result.GetApplied() != expectedApplied[i] || selected != expectedLayers[i]) {
return unexpected(names[i]);
}
}
return true;
}
히트 테스트
지도 뷰의 HitTest(point)는 화면 점에 그려진 피처를 하나 찾습니다. 선택 서비스와는 별개이며, 선택을 읽지도 바꾸지도 않습니다.
히트 테스트 (glsMapView::HitTest) |
점으로 선택 (ExecuteAtScreenPoint) |
|
|---|---|---|
| 결과 | 피처 하나(레이어 id와 피처 id) | 대상 레이어의 맞은 피처 전부, 또는 SingleHit으로 고른 하나 |
| 선택 | 바꾸지 않음 | 적용 모드대로 씀, 다른 레이어의 선택을 지움 |
| 반지름 | 기본 6픽셀. 옵션(glsHitTestOptions)으로 1~128픽셀 |
인자로 줌(1 이상) |
| 대상 레이어 | 맨 위부터. 레이어 자신이 보이고 선택 가능하며(히트맵 제외), 품은 그룹이 모두 보이고 지금 축척이 그룹의 축척 범위 안 | 후보 레이어 가운데 맨 위부터 |
HitTest는 지금 뷰의 히트 테스트 자료를 준비하는 동안 막힐 수 있습니다. 막히지 않아야 하면 SetHitTestInterest로 관심을 켜 두고 TryHitTest를 쓰세요. 관심이 켜져 있으면 그리기가 히트 테스트 자료도 함께 준비하며, TryHitTest는 자료가 아직 없으면 NotReady를 돌려줍니다.
예제는 districts에 id로 선택을 하나 둔 뒤 Spice Market 위에서 히트 테스트를 해 places의 피처 5를 얻고, 선택이 districts의 1건 그대로임을 확인합니다. 구멍 한가운데의 히트 테스트는 맞은 것이 없습니다.
HitTest(glsScreenPoint, glsHitTestResult*, bool* outHit)는 맞은 것이 없어도 성공하고 *outHit이 false입니다. 결과의 문자열과 배열 포인터(LayerId 등)는 지도 뷰 래퍼가 가지며 같은 래퍼의 다음 히트 테스트까지만 유효하므로, 보관하려면 복사합니다. 피처 id는 HasFeatureId가 true일 때만 뜻이 있습니다.
// A hit test asks which feature is drawn at a screen point; it does not read
// or change the selection. The strings in the result stay valid until the
// next hit test on the same view, so they are copied.
static bool hitTest(GDK::glsSelectionService& selection, const GDK::glsMapView& view)
{
const int64_t oldHarbor[] = {1};
if (!succeeded(selection.SetSelectedIds("districts", oldHarbor, 1))) {
return false;
}
GDK::glsScreenPoint screen;
if (!toScreen(view, kSpiceMarket, screen)) {
return false;
}
GDK::glsHitTestResult hit;
bool found = false;
if (!succeeded(view.HitTest(screen, &hit, &found))) {
return false;
}
const std::string layer = found && hit.LayerId ? hit.LayerId : "";
const int64_t feature = found && hit.HasFeatureId ? hit.FeatureId : -1;
std::printf("[sample] hit test on Spice Market: layer %s, feature %" PRId64 "\n", layer.c_str(), feature);
const std::string selected = selectedLayerId(selection);
const int districts = selected.empty() ? -1 : selectedCount(selection, "districts");
if (districts < 0) {
return false; // selectedLayerId or selectedCount has printed why
}
std::printf("[sample] selected layer after the hit test: %s, %d selected\n", selected.c_str(), districts);
if (!toScreen(view, kEmptySpot, screen) || !succeeded(view.HitTest(screen, &hit, &found))) {
return false;
}
std::printf("[sample] hit test on an empty spot: hit %s\n", yesNo(found));
return (layer == "places" && feature == 5 && selected == "districts" && districts == 1 && !found) ||
unexpected("expected a hit on places and an unchanged selection");
}
모두 지우기
ClearAll()은 선택이 있는 모든 피처 레이어(id가 빈 레이어는 빼고)의 선택을 지웁니다. 숨겨졌거나 선택 불가인 레이어와 그룹 안의 레이어도 지웁니다. 한 레이어만 지우려면 ClearSelection(layerId)를 씁니다.
// ClearAll clears every feature layer that has a selection, also layers that
// are hidden or not selectable.
static bool clearAll(GDK::glsSelectionService& selection, const GDK::glsMapView& view)
{
const int64_t twoPlaces[] = {1, 2};
LayerPtr places = layerById(view, "places");
if (!places || !succeeded(selection.SetSelectedIds("places", twoPlaces, 2)) ||
!succeeded(places->SetSelectable(false)) || !succeeded(selection.ClearAll())) {
return false;
}
const int left = selectedCount(selection, "places");
const std::string selected = left < 0 ? std::string() : selectedLayerId(selection);
if (selected.empty()) {
return false; // selectedCount or selectedLayerId has printed why
}
std::printf("[sample] after ClearAll: selected layer %s, places has %d selected\n", selected.c_str(), left);
return (left == 0 && selected == "(none)") || unexpected("expected no selection");
}
실패와 오류 종류
선택 서비스가 찾아낸 실패는 상세 정보로 보고됩니다. 영역(Domain)은 Selection이고, 종류(Kind)는 glsSelectionErrorKind 값입니다. 일부 실패는 메시지만 남기고 Selection 상세 정보를 남기지 않습니다. 예를 들어 문자열 버퍼가 작을 때(InvalidArgument)와 예기치 않은 내부 오류(UnknownError)가 그렇습니다. 자주 만나는 종류는 다음과 같습니다.
| 종류 | 결과 코드 | 경우 |
|---|---|---|
LayerIdEmpty |
InvalidArgument |
레이어 id가 비었음 |
LayerNotFound |
NotFound |
그 id의 레이어가 지도에 없음 |
NotFeatureLayer |
NotSupported |
피처 레이어가 아님 |
TooFewSelectionPoints |
InvalidArgument |
다각형의 꼭짓점이 3개보다 적음 |
NoVisibleSelectableLayers |
NotFound |
후보 레이어가 없음 |
NoSelectedFeatures |
NotFound |
선택이 없는데 선택이 있는 레이어나 범위를 물음 |
glsSelectionErrorKind, glsSelectionWarning, glsSelectionApplyMode, glsSelectionSpatialOperation의 값은 고정되어 있습니다(값이 고정된 열거형). 메시지는 영어 진단 문장이므로, 화면에 보일 문구는 응용 프로그램이 오류 종류로 만드세요.
호출이 돌려준 glsStatus가 실패면 바로 뒤에 glsGetLastErrorDetail()로 상세 정보를 읽습니다. 예제의 NotSelectable이 이렇게 합니다.
다음 장
다음은 10장 편집입니다. 지도의 레이어에서 피처를 더하고 고치고 지우고, 되돌리고, 저장하는 방법을 설명합니다.