Java REST SDK 개발자 가이드(미리 보기)

Azure Maps Java SDK를 Java 애플리케이션 및 라이브러리와 통합하여 지도 관련 및 위치 인식 애플리케이션을 빌드할 수 있습니다. Azure Maps Java SDK에는 검색, 경로, 렌더링, 지리적 위치, 교통, 표준 시간대 및 날씨에 대한 API가 포함되어 있습니다. 이러한 API는 주소 검색, 서로 다른 좌표 간 라우팅, 특정 IP 주소의 지리적 위치 가져오기 등의 작업을 지원합니다.

참고 항목

Azure Maps Java SDK는 최신 Java 장기 지원 릴리스(현재 Java 18)까지 테스트 및 전달 지원을 포함하며 Java 8을 기준으로 합니다. 다운로드할 Java 버전 목록은 Java 표준 버전을 참조하세요.

필수 조건

프로그래밍 방식으로 Azure Maps 계정을 만들 수 있습니다. 다음은 Azure CLI를 사용하는 예입니다.

az maps account create --kind "Gen2" --account-name "myMapAccountName" --resource-group "<resource group>" --sku "G2"

Maven 프로젝트 만들기

다음 PowerShell 코드 조각은 PowerShell을 사용하여 maven 프로젝트를 만드는 방법을 보여 줍니다. 먼저 maven 명령을 실행하여 maven 프로젝트를 만듭니다.

mvn archetype:generate "-DgroupId=groupId" "-DartifactId=DemoProject" "-DarchetypeArtifactId=maven-archetype-quickstart" "-DarchetypeVersion=1.4" "-DinteractiveMode=false" 
매개 변수 설명
-DGroupId 그룹 ID는 모든 프로젝트에서 프로젝트를 고유하게 식별합니다.
-DartifactId 프로젝트 이름. 새 폴더로 만들어집니다.
-DarchetypeArtifactId 프로젝트 형식. maven-archetype-quickstart는 샘플 프로젝트를 생성합니다.
-DinteractiveMode false로 설정하면 기본 옵션이 적용된 빈 Java 프로젝트가 생성됩니다.

패키지 설치

Azure Maps Java SDK를 사용하려면 필요한 모든 패키지를 설치해야 합니다. Azure Maps의 각 서비스는 자체 패키지에서 사용할 수 있습니다. Azure Maps 서비스에는 검색, 렌더링, 교통, 날씨 등이 포함됩니다. 프로젝트에 사용되는 서비스에 대한 패키지만 설치하면 됩니다.

maven 프로젝트가 만들어지면 그룹 ID, 이름, 아티팩트 ID와 같은 기본 정보가 포함된 pom.xml 파일이 있어야 합니다. 다음으로, 다음 예제와 같이 각 Azure Maps 서비스에 대한 종속성을 추가합니다.

<dependency> 
  <groupId>com.azure</groupId> 
  <artifactId>azure-maps-search</artifactId> 
  <version>1.0.0-beta.1</version> 
</dependency> 
<dependency> 
  <groupId>com.azure</groupId> 
  <artifactId>azure-maps-route</artifactId> 
  <version>1.0.0-beta.1</version> 
</dependency> 
<dependency> 
  <groupId>com.azure</groupId> 
  <artifactId>azure-maps-render</artifactId> 
  <version>1.0.0-beta.1</version> 
</dependency> 
<dependency> 
  <groupId>com.azure</groupId> 
  <artifactId>azure-maps-traffic</artifactId> 
  <version>1.0.0-beta.1</version> 
</dependency> 
<dependency> 
  <groupId>com.azure</groupId> 
  <artifactId>azure-maps-weather</artifactId> 
  <version>1.0.0-beta.1</version> 
</dependency> 
<dependency> 
  <groupId>com.azure</groupId> 
  <artifactId>azure-maps-timezone</artifactId> 
  <version>1.0.0-beta.1</version> 
</dependency> 

프로젝트에서 mvn clean install을 실행한 다음, demo.java라는 Java 파일을 만들고 Azure 지도에서 필요한 항목을 파일로 가져옵니다.

cd DemoProject
New-Item demo.java

mvn clean install을 실행하면 오류가 발생하는 경우 mvn clean install -U를 실행해 보세요.

Azure Maps 서비스

서비스 이름 Maven 패키지 샘플
Search azure-maps-search 검색 샘플
라우팅 azure-maps-routing  라우팅 샘플
렌더링 azure-maps-rendering 렌더링 샘플
지리적 위치 azure-maps-geolocation 지리적 위치 샘플
표준 시간대 azure-maps-timezone 표준 시간대 샘플

MapsSearchClient 만들기 및 인증

Azure Maps Search API에 액세스하는 데 사용되는 클라이언트 개체에는 Azure Maps 구독 키를 사용할 때 인증할 AzureKeyCredential 개체 또는 Microsoft Entra ID를 사용하여 인증을 받을 때 Azure Maps 클라이언트 ID가 있는 TokenCredential 개체가 필요합니다. 자세한 내용은 Azure Maps로 인증을 참조하세요.

Microsoft Entra 자격 증명 사용

Azure ID 라이브러리를 사용하여 Microsoft Entra ID로 인증을 받을 수 있습니다. DefaultAzureCredential 공급자를 사용하려면 pom.xml 파일에 mvn 종속성을 추가해야 합니다.

<dependency>
  <groupId>com.azure</groupId>
  <artifactId>azure-identity</artifactId>
</dependency>

새 Microsoft Entra 애플리케이션을 등록하고 필요한 역할을 서비스 주체에 할당하여 Azure Maps에 대한 액세스 권한을 부여해야 합니다. 자세한 내용은 비 Azure 리소스의 디먼 호스트를 참조하세요. 애플리케이션(클라이언트) ID, 디렉터리(테넌트) ID 및 클라이언트 암호가 반환됩니다. 이 값을 복사하여 안전한 장소에 저장합니다. 다음 단계에서 필요합니다.

애플리케이션(클라이언트) ID, 디렉터리(테넌트) ID, Microsoft Entra 애플리케이션의 클라이언트 암호 및 맵 리소스의 클라이언트 ID 값을 환경 변수로 설정합니다.

환경 변수 설명
AZURE_CLIENT_ID 등록된 애플리케이션의 애플리케이션(클라이언트) ID
AZURE_CLIENT_SECRET 등록된 애플리케이션의 클라이언트 암호 값
AZURE_TENANT_ID 등록된 애플리케이션의 디렉터리(테넌트) ID
MAPS_CLIENT_ID Azure Maps 계정의 클라이언트 ID

이제 PowerShell에서 환경 변수를 만들어 다음 값을 저장할 수 있습니다.

$Env:AZURE_CLIENT_ID="<client-id>"
A$Env:AZURE_CLIENT_SECRET="<client-secret>"
$Env:AZURE_TENANT_ID="<tenant-id>"
$Env:MAPS_CLIENT_ID="<maps-client-id>"

환경 변수를 설정한 후 프로그램에서 사용하여 AzureMapsSearch 클라이언트를 인스턴스화할 수 있습니다.

import com.azure.identity.DefaultAzureCredential;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.maps.search.MapsSearchClient;
import com.azure.maps.search.MapsSearchClientBuilder;

public class Demo {
    public static void main( String[] args) {
        MapsSearchClientBuilder builder = new MapsSearchClientBuilder();
        DefaultAzureCredential tokenCredential = new DefaultAzureCredentialBuilder().build();
        builder.credential(tokenCredential);
        builder.mapsClientId(System.getenv("MAPS_CLIENT_ID"));
        MapsSearchClient client = builder.buildClient();
    }
}

Important

이전 코드 조각에서 만든 다른 환경 변수는 코드 샘플에서는 사용되지 않지만 DefaultAzureCredential()에서 필요합니다. 동일한 명명 규칙을 사용하여 이러한 환경 변수를 올바르게 설정하지 않으면 런타임 오류가 발생합니다. 예를 들어 AZURE_CLIENT_ID가 누락되었거나 잘못된 경우 InvalidAuthenticationTokenTenant 오류가 발생합니다.

구독 키 자격 증명 사용

Azure Maps 구독 키로 인증할 수 있습니다. 구독 키는 다음 스크린샷과 같이 Azure Maps 계정의 인증 섹션에서 찾을 수 있습니다.

Screenshot showing your Azure Maps subscription key in the Azure portal.

이제 PowerShell에서 환경 변수를 만들어 구독 키를 저장할 수 있습니다.

$Env:SUBSCRIPTION_KEY="<subscription-key>"

환경 변수가 만들어지면 코드에서 액세스할 수 있습니다.

import com.azure.core.credential.AzureKeyCredential;
import com.azure.maps.search.MapsSearchClient;
import com.azure.maps.search.MapsSearchClientBuilder;

public class Demo {
    public static void main( String[] args) {

        // Use Azure Maps subscription key authentication
        MapsSearchClientBuilder builder = new MapsSearchClientBuilder();
        AzureKeyCredential keyCredential = new AzureKeyCredential(System.getenv("SUBSCRIPTION_KEY"));
        builder.credential(keyCredential);
        MapsSearchClient client = builder.buildClient();
    }
}

엔터티에 대한 퍼지 검색

다음 코드 조각은 간단한 콘솔 애플리케이션에서 azure-maps-search 패키지를 가져오고 시애틀 근처의 "Starbucks"에 대해 퍼지 검색을 수행하는 방법을 보여 줍니다.

import java.io.IOException;
import com.azure.core.credential.AzureKeyCredential;
import com.azure.core.models.GeoPosition;
// Enable the 2 imports below if you want to use AAD authentication 
// import com.azure.identity.DefaultAzureCredential;
// import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.maps.search.MapsSearchClient;
import com.azure.maps.search.MapsSearchClientBuilder;
import com.azure.maps.search.models.FuzzySearchOptions;
import com.azure.maps.search.models.SearchAddressResult;
import com.azure.maps.search.models.SearchAddressResultItem;

public class Demo {
    public static void main( String[] args) throws IOException {
    MapsSearchClientBuilder builder = new MapsSearchClientBuilder();
    
    // Instantiate with key credential. Get SUBSCRIPTION_KEY from environment variable: 
    AzureKeyCredential keyCredential = new AzureKeyCredential(System.getenv("SUBSCRIPTION_KEY"));
    builder.credential(keyCredential);
    
    // Or you can also instantiate with token credential: 
    // DefaultAzureCredential tokenCredential = new DefaultAzureCredentialBuilder().build();
    // builder.credential(tokenCredential);
    // builder.mapsClientId(System.getenv("MAPS_CLIENT_ID"));
    MapsSearchClient client = builder.buildClient();
    
    // Fuzzy search with options: 
    SearchAddressResult results = client.fuzzySearch(new FuzzySearchOptions("starbucks", new GeoPosition(-122.34255, 47.61010)));
    
    // Print the search results:
    for (SearchAddressResultItem item : results.getResults()) {
              MapsSearchAddress address = item.getAddress();
             GeoPosition coordinate = item.getPosition();
             System.out.format(
                 "* %s, %s\\n" +
                 "  %s %s %s\\n" +
                 "  Coordinate: (%.4f, %.4f)\\n",
                 address.getStreetNumber(), address.getStreetName(),
                 address.getMunicipality(), address.getCountryCode(), address.getPostalCode(),
                 coordinate.getLatitude(), coordinate.getLongitude());
        }
    }
}

이 코드 조각은 Azure 자격 증명을 사용하여 MapsSearchClient 개체를 만드는 방법을 보여 줍니다. 먼저 Azure Maps 구독 키를 사용하여 AzureKeyCredential을 인스턴스화한 다음, 자격 증명을 전달하여 MapsSearchClient를 인스턴스화합니다. FuzzySearch와 같은 MapsSearchClient 메서드는 POI(Point of Interest) 이름 "Starbucks" 및 좌표 GeoPosition(-122.31, 47.61)을 사용할 수 있습니다.

명령줄의 프로젝트 폴더에서 프로그램을 실행합니다.

java .\demo.java

스타벅스 주소 목록과 좌표 결과가 표시됩니다.

* 1912, Pike Place
  Seattle US 98101
  Coordinate: (47.6102, -122.3425)
* 2118, Westlake Avenue
  Seattle US 98121
  Coordinate: (47.6173, -122.3378)
* 2601, Elliott Avenue
  Seattle US 98121
  Coordinate: (47.6143, -122.3526)
* 1730, Howell Street
  Seattle US 98101
  Coordinate: (47.6172, -122.3298)
* 220, 1st Avenue South
  Seattle US 98104
  Coordinate: (47.6003, -122.3338)
* 400, Occidental Avenue South
  Seattle US 98104
  Coordinate: (47.5991, -122.3328)
* 1600, East Olive Way
  Seattle US 98102
  Coordinate: (47.6195, -122.3251)
* 500, Mercer Street
  Seattle US 98109
  Coordinate: (47.6250, -122.3469)
* 505, 5Th Ave S
  Seattle US 98104
  Coordinate: (47.5977, -122.3285)
* 425, Queen Anne Avenue North
  Seattle US 98109
  Coordinate: (47.6230, -122.3571)

주소 검색

SearchAddress 메서드를 호출하여 주소의 좌표를 가져옵니다. 다음과 같이 샘플에서 Main 프로그램을 수정합니다.

import java.io.IOException;
import com.azure.core.credential.AzureKeyCredential;
import com.azure.core.models.GeoPosition;
// Enable the 2 imports below if you want to use AAD authentication 
// import com.azure.identity.DefaultAzureCredential;
// import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.maps.search.MapsSearchClient;
import com.azure.maps.search.MapsSearchClientBuilder;
import com.azure.maps.search.models.SearchAddressOptions;
import com.azure.maps.search.models.SearchAddressResult;
import com.azure.maps.search.models.SearchAddressResultItem;

public class Demo {
    public static void main( String[] args) throws IOException {
    MapsSearchClientBuilder builder = new MapsSearchClientBuilder();
    
    // Instantiate with key credential: 
    AzureKeyCredential keyCredential = new  
        AzureKeyCredential(System.getenv("SUBSCRIPTION_KEY"));
    builder.credential(keyCredential);
    
    // Or you can also instantiate with token credential: 
    // DefaultAzureCredential tokenCredential = new DefaultAzureCredentialBuilder().build();
    // builder.credential(tokenCredential);
    // builder.mapsClientId(System.getenv("MAPS_CLIENT_ID"));
    
    MapsSearchClient client = builder.buildClient();
    client.searchAddress(new SearchAddressOptions("15127 NE 24th Street, Redmond, WA 98052"));
    
    // Search address with options and return top 5 results: 
    SearchAddressResult results = client.searchAddress(new SearchAddressOptions("1  
        Main Street").setCoordinates(new GeoPosition(-74.011454,  
        40.706270)).setRadiusInMeters(40000).setTop(5));
    
    // Print results: 
    if (results.getResults().size() > 0) {
        SearchAddressResultItem item = results.getResults().get(0);
        System.out.format("The coordinates is (%.4f, %.4f)", 
            item.getPosition().getLatitude(), item.getPosition().getLongitude());
        }
    }
}

이 샘플에서 client.SearchAddress 메서드는 신뢰도 점수로 정렬된 결과를 반환하고 첫 번째 결과의 좌표를 출력합니다.

Azure Maps Search는 일부 일괄 처리 쿼리 방법도 제공합니다. 이러한 메서드는 LRO(Long Running Operations) 개체를 반환합니다. 요청이 모든 결과를 즉시 반환하지 않을 수 있으므로 완료될 때까지 기다리거나 일괄 처리 역방향 검색 방법에 설명된 것처럼 주기적으로 결과를 쿼리하도록 선택할 수 있습니다.

import java.util.ArrayList;
import java.util.List;
import com.azure.core.credential.AzureKeyCredential;
import com.azure.core.models.GeoPosition;
// Enable the 2 imports below if you want to use AAD authentication
// import com.azure.identity.DefaultAzureCredential;
// import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.maps.search.MapsSearchClient;
import com.azure.maps.search.MapsSearchClientBuilder;
import com.azure.maps.search.models.BatchReverseSearchResult;
import com.azure.maps.search.models.ReverseSearchAddressBatchItem;
import com.azure.maps.search.models.ReverseSearchAddressOptions;
import com.azure.maps.search.models.ReverseSearchAddressResultItem;

public class Demo{
    public static void main( String[] args) throws IOException {
        MapsSearchClientBuilder builder = new MapsSearchClientBuilder();
        
        // Instantiate with key credential:
        AzureKeyCredential keyCredential = new 
        AzureKeyCredential(System.getenv("SUBSCRIPTION_KEY"));
        builder.credential(keyCredential);
        
        // Or you can also instantiate with token credential: 
        // DefaultAzureCredential tokenCredential = new DefaultAzureCredentialBuilder().build();
        // builder.credential(tokenCredential);
        // builder.mapsClientId(System.getenv("MAPS_CLIENT_ID"));
        
        MapsSearchClient client = builder.buildClient();
        List<ReverseSearchAddressOptions> reverseOptionsList = new ArrayList<>();
        reverseOptionsList.add(new ReverseSearchAddressOptions(new GeoPosition(2.294911, 48.858561)));
        reverseOptionsList.add(new ReverseSearchAddressOptions(new GeoPosition(-122.34255, 47.61010)));
        reverseOptionsList.add(new ReverseSearchAddressOptions(new GeoPosition(-122.33817, 47.61559)).setRadiusInMeters(5000));
        BatchReverseSearchResult batchReverseSearchResult = 
        client.beginReverseSearchAddressBatch(reverseOptionsList).getFinalResult();
        for (ReverseSearchAddressBatchItem item : batchReverseSearchResult.getBatchItems()) {
            for (ReverseSearchAddressResultItem result : item.getResult().getAddresses()) {
                System.out.println(result.getAddress().getFreeformAddress());
            }
        }
    }
}