클라이언트 라이브러리 설치

Google Street View Publish API는 HTTP 및 JSON에 기반하므로 모든 표준 HTTP 클라이언트가 API에 요청을 전송하고 응답을 파싱할 수 있습니다.

그러나 Google API 클라이언트 라이브러리는 우수한 언어 통합, 향상된 보안, 사용자 승인이 필요한 호출에 대한 지원을 제공합니다. 이 클라이언트 라이브러리는 다양한 프로그래밍 언어로 제공되므로 HTTP 요청을 직접 설정하고 응답을 파싱하지 않아도 됩니다.

시작하려면 개발에 사용할 프로그래밍 언어를 선택합니다. 아직 더 많은 언어를 추가하고 있습니다.

Python

gapic-google-maps-streetview_publish에 대한 Python Package Index 안내를 참조하세요.

이 모듈을 설치한 후 다음 코드로 모듈을 테스트하여 사진을 업로드할 수 있습니다.

from google.streetview.publish_v1.proto import resources_pb2
from google.streetview.publish_v1 import street_view_publish_service_client as client
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.file import Storage
from oauth2client.tools import run_flow
import google.oauth2.credentials
import requests
import time

def get_access_token():
  client_id = 'Your client ID'
  client_secret = 'Your client secret'
  flow = OAuth2WebServerFlow(client_id=client_id,
                             client_secret=client_secret,
                             scope='https://www.googleapis.com/auth/streetviewpublish',
                             redirect_uri='http://example.com/auth_return')
  storage = Storage('creds.data')
  # Open a web browser to ask the user for credentials.
  credentials = run_flow(flow, storage)
  assert credentials.access_token is not None
  return credentials.access_token

token = get_access_token()
credentials = google.oauth2.credentials.Credentials(token)

# Create a client and request an Upload URL.
streetview_client = client.StreetViewPublishServiceClient(credentials=credentials)
upload_ref = streetview_client.start_upload()
print("Created upload URL: " + str(upload_ref))

# Upload the photo bytes to the Upload URL.
with open("/path/to/your/file.jpg", "rb") as f:
  print("Uploading file: " + f.name)
  raw_data = f.read()
  headers = {
      "Authorization": "Bearer " + token,
      "Content-Type": "image/jpeg",
      "X-Goog-Upload-Protocol": "raw",
      "X-Goog-Upload-Content-Length": str(len(raw_data)),
  }
  r = requests.post(upload_ref.upload_url, data=raw_data, headers=headers)
  print("Upload response: " + str(r))

# Upload the metadata of the photo.
photo = resources_pb2.Photo()
photo.upload_reference.upload_url = upload_ref.upload_url
photo.capture_time.seconds = int(time.time())
photo.pose.heading = 105.0
photo.pose.lat_lng_pair.latitude = 46.7512623
photo.pose.lat_lng_pair.longitude = -121.9376983
create_photo_response = streetview_client.create_photo(photo)
print("Create photo response: " + str(create_photo_response))

Java

maven에서 자바 라이브러리를 참조하세요.

이 라이브러리가 설치되면 다음 코드로 테스트하여 사진을 업로드할 수 있습니다.

/*
 * This code sample shows how to upload a photo with the Street View Publish API.
 * View the complete project sample at
 * https://github.com/google/google-api-java-client-samples/tree/master/streetview-publish-cmdline-sample.
 *
 */
package com.google.api.services.samples.streetview.publish.cmdline;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.DataStoreFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.Credentials;
import com.google.geo.ugc.streetview.publish.v1.StreetViewPublishResources.Photo;
import com.google.geo.ugc.streetview.publish.v1.StreetViewPublishResources.Pose;
import com.google.geo.ugc.streetview.publish.v1.StreetViewPublishResources.UploadRef;
import com.google.geo.ugc.streetview.publish.v1.StreetViewPublishServiceGrpc;
import com.google.protobuf.Empty;
import com.google.protobuf.Timestamp;
import com.google.streetview.publish.v1.StreetViewPublishServiceClient;
import com.google.streetview.publish.v1.StreetViewPublishServiceSettings;
import com.google.type.LatLng;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.EntityBuilder;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

public class StreetViewPublishSample {

  /**
   * Be sure to specify the name of your application. If the application name is {@code null} or
   * blank, the application will log a warning. Suggested format is "MyCompany-ProductName/1.0".
   */
  private static final String APPLICATION_NAME = "";

  /** Directory to store user credentials. */
  private static final java.io.File DATA_STORE_DIR =
      new java.io.File(System.getProperty("user.home"), ".store/streetview_publish_sample");

  /**
   * Global instance of the {@link DataStoreFactory}. The best practice is to make it a single
   * globally shared instance across your application.
   */
  private static FileDataStoreFactory dataStoreFactory;

  /** Global instance of the HTTP transport. */
  private static HttpTransport httpTransport;

  /** Global instance of the JSON factory. */
  private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();

  private static Credential credential;

  /** Authorizes the installed application to access user's protected data. */
  private static Credential authorize() throws Exception {
    // load client secrets
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
        new InputStreamReader(StreetViewPublishSample.class.getResourceAsStream("/client_secrets.json")));
    if (clientSecrets.getDetails().getClientId().startsWith("Enter")
        || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
      System.out.println(
          "Enter Client ID and Secret from https://console.cloud.google.com/apis/credentials "
          + "into streetview-publish-cmdline-sample/src/main/resources/client_secrets.json");
      System.exit(1);
    }
    // set up authorization code flow
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
        httpTransport, JSON_FACTORY, clientSecrets,
        Arrays.asList("https://www.googleapis.com/auth/streetviewpublish")
        ).setDataStoreFactory(
        dataStoreFactory).build();
    // authorize
    return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
  }

  public static void main(String[] args) {
    try {
      httpTransport = GoogleNetHttpTransport.newTrustedTransport();
      dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);

      // Authorize.
      credential = authorize();
      System.out.println("Access token: " + credential.getAccessToken());

      // Build a client to interact with the API.
      StreetViewPublishServiceSettings settings =
        StreetViewPublishServiceSettings.defaultBuilder()
          .setCredentialsProvider(FixedCredentialsProvider.create(new Credentials() {
              public String getAuthenticationType() {
                return "OAuth2";
              }
              public Map<String, List<String>> getRequestMetadata(URI uri) throws IOException {
                Map<String, List<String>> map = new HashMap<String, List<String>>();
                List<String> list = new ArrayList<String>();
                list.add("Bearer " + credential.getAccessToken());
                map.put("Authorization", list);
                return map;
              }
              public boolean hasRequestMetadata() { return true; }
              public boolean hasRequestMetadataOnly() { return true; }
              public void refresh() throws IOException { }
          }))
          .build();
      StreetViewPublishServiceClient client = StreetViewPublishServiceClient.create(settings);

      // Request upload url.
      UploadRef uploadRef = client.startUploadCallable().futureCall(Empty.newBuilder().build()).get();
      System.out.println("Requested upload url: " + uploadRef);

      // Upload photo bytes.
      HttpPost request = new HttpPost(uploadRef.getUploadUrl());
      request.addHeader("Authorization", "Bearer " + credential.getAccessToken());
      request.addHeader("Content-Type", "image/jpeg");
      request.addHeader("x-Goog-Upload-protocol", "raw");
      URL url = StreetViewPublishSample.class.getResource("/sample.jpg");
      Path path = Paths.get(url.toURI());
      byte[] data = Files.readAllBytes(path);
      request.addHeader("X-Goog-Upload-Content-Length", String.valueOf(data.length));
      request.setEntity(EntityBuilder.create().setBinary(data).build());

      HttpClient httpClient = new DefaultHttpClient();
      HttpResponse response = httpClient.execute(request);
      System.out.println("Http response: " + response);

      // Upload photo metadata.
      Photo photo = client.createPhoto(Photo.newBuilder()
          .setUploadReference(uploadRef)
          .setCaptureTime(Timestamp.newBuilder().setSeconds(System.currentTimeMillis() / 1000))
          .setPose(Pose.newBuilder()
            .setHeading(105d)
            .setLatLngPair(LatLng.newBuilder()
              .setLatitude(46.7512623d)
              .setLongitude(-121.9376983d)
              .build())
            .build()
            )
          .build());

      System.out.println("Uploaded photo metadata: " + photo);
      return;
    } catch (IOException e) {
      System.err.println(e.getMessage());
    } catch (Throwable t) {
      t.printStackTrace();
    }
    System.exit(1);
  }

}

NodeJs

streetview-publish-client-libraries-v1에서 NPM 설치 안내를 참조하세요.

Go

cloud.google.com/go/streetview/publish/apiv1/publishpb에서 Go 설치 안내를 참조하세요.