访问Fusion表以使用FusionTableMap API在Map中显示

时间:2012-12-20 10:34:13

标签: google-maps-api-3 oauth google-fusion-tables

我在google中创建了服务帐户以访问和上传融合表中的数据。我可以使用OAuth进行身份验证并将数据推送到服务帐户的融合表中。但是当我尝试使用tableid访问同一个表时在地图中我无法访问相同。创建的表格没有显示在我的主帐户中。我在stackoverflow中读到了一些他们谈到过FT的问题(我甚至无法做到这一点)

我的代码:

/

*
 * Copyright (c) 2012 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package com.google.api.services.samples.fusiontables.cmdline;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.DateTime;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.Drive.Permissions;
import com.google.api.services.drive.model.Permission;
import com.google.api.services.fusiontables.Fusiontables;
import com.google.api.services.fusiontables.Fusiontables.Query.Sql;
import com.google.api.services.fusiontables.Fusiontables.Table.Delete;
import com.google.api.services.fusiontables.FusiontablesScopes;
import com.google.api.services.fusiontables.model.Column;
import com.google.api.services.fusiontables.model.Sqlresponse;
import com.google.api.services.fusiontables.model.Table;
import com.google.api.services.fusiontables.model.TableList;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.UUID;

/**
 * @author Christian Junk
 * 
 */
public class FusionTablesSample {

  /** E-mail address of the service account. */
  private static final String SERVICE_ACCOUNT_EMAIL = "XXXXXXXXXXXXXX@developer.gserviceaccount.com";




  /** Global instance of the HTTP transport. */
  private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();

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

  private static Fusiontables fusiontables;

  /** Authorizes the installed application to access user's protected data. */
  private static Credential authorizeNew() throws Exception {

            // Build service account credential.
        GoogleCredential credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT)
        .setJsonFactory(JSON_FACTORY)
        .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)


        .setServiceAccountScopes(FusiontablesScopes.FUSIONTABLES)
        .setServiceAccountPrivateKeyFromP12File(new File("key.p12"))
        .build();



       return credential;
  }

  /** Authorizes the installed application to access user's protected data. */
  private static Credential authorizeNewDrive() throws Exception {

      GoogleCredential credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT)
      .setJsonFactory(JSON_FACTORY)
      .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)


      .setServiceAccountScopes(DriveScopes.DRIVE)
      .setServiceAccountPrivateKeyFromP12File(new File("key.p12"))
      .build();



     return credential;
  }






  /**
   * Insert a new permission.
   *
   * @param service Drive API service instance.
   * @param fileId ID of the file to insert permission for.
   * @param value User or group e-mail address, domain name or {@code null}
                  "default" type.
   * @param type The value "user", "group", "domain" or "default".
   * @param role The value "owner", "writer" or "reader".
   * @return The inserted permission if successful, {@code null} otherwise.
   */
  private static Permission insertPermission(Drive service, String fileId,
      String value, String type, String role) {
    Permission newPermission = new Permission();

    newPermission.setValue(value);
    newPermission.setType(type);
    newPermission.setRole(role);
   try {
       System.out.println("service"+service.permissions());
      return service.permissions().insert(fileId, newPermission).execute();
      } catch (IOException e) {
     System.out.println("An error occurred: " + e);
   }
    return null;
  }

  /** Global Drive API client. */
  private static Drive drive;

  public static void main(String[] args) {
    try {
      try {



//        System.out.println(System.getProperty("user.home"));
        // authorization
        Credential credential = authorizeNew();

        Credential credential1 = authorizeNewDrive();


        // set up global FusionTables instance
        fusiontables = new Fusiontables.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(
            "FusionTable").build();


        // set up the global Drive instance
        drive = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential1).setApplicationName(
            "FusionTable").build();


        System.out.println(drive.files().list());
        Permissions perms=drive.permissions();
        System.out.println(perms);



        // run commands
//        listTables();
        ArrayList<String> list=listTables("");

//       String tableId = createTable();
//        insertData(tableId);
        for(String tableid:list)
        {
            insertPermission(drive, tableid, "XXXXXXXXX@gmail.com","anyone","owner");
//          System.out.print(" permission for table id is  " + perms.list(tableid));
        showRows(tableid);
//        deleteTable(tableid);
        }
        listTables();
   //     deleteTable(tableId);
        // success!
        return;
      } catch (IOException e) {
        System.err.println(e.getMessage());
      }
    } catch (Throwable t) {
      t.printStackTrace();
    }
    System.exit(1);
  }

  /**
   * @param tableId
   * @throws IOException
   */
  private static void showRows(String tableId) throws IOException {
    View.header("Start Showing Rows From Table");

    Sql sql = fusiontables.query().sql("SELECT Text,Number,Location,Address,Date FROM " + tableId);

    try {
     Sqlresponse response= sql.execute();
     System.out.println(  response.getColumns());
   System.out.println(  response.getRows());

    } catch (IllegalArgumentException e) {
      // For google-api-services-fusiontables-v1-rev1-1.7.2-beta this exception will always
      // been thrown.
      // Please see issue 545: JSON response could not be deserialized to Sqlresponse.class
      // http://code.google.com/p/google-api-java-client/issues/detail?id=545
    }
    View.header("End Showing Rows From Table");
  }

  /** List tables for the authenticated user. */
  private static void listTables() throws IOException {
    View.header("Listing My Tables");

    // Fetch the table list
    Fusiontables.Table.List listTables = fusiontables.table().list();
    TableList tablelist = listTables.execute();

    if (tablelist.getItems() == null || tablelist.getItems().isEmpty()) {
      System.out.println("No tables found!");
      return;
    }

    for (Table table : tablelist.getItems()) {
      View.show(table);
      View.separator();
    }
  }

  private static  ArrayList<String> listTables(String a) throws IOException {
    View.header("Listing My Tables");
    ArrayList<String> rt=new ArrayList<String>();
    // Fetch the table list
    Fusiontables.Table.List listTables = fusiontables.table().list();
    TableList tablelist = listTables.execute();

    if (tablelist.getItems() == null || tablelist.getItems().isEmpty()) {
      System.out.println("No tables found!");
      return rt;
    }

    for (Table table : tablelist.getItems()) {
      rt.add(table.getTableId());
      View.show(table);
      View.separator();
    }
    return rt;
  }

  /** Create a table for the authenticated user. */
  private static String createTable() throws IOException {
    View.header("Create Sample Table");

    // Create a new table
    Table table = new Table();
    table.setName(UUID.randomUUID().toString());
    table.setIsExportable(true);

    table.setDescription("Sample Table");

    // Set columns for new table
    table.setColumns(Arrays.asList(new Column().setName("Text").setType("STRING"),
        new Column().setName("Number").setType("NUMBER"),
        new Column().setName("Location").setType("LOCATION"),
        new Column().setName("Address").setType("STRING"),
        new Column().setName("Date").setType("DATETIME")));

    // Adds a new column to the table.
    Fusiontables.Table.Insert t = fusiontables.table().insert(table);
    Table r = t.execute();

    View.show(r);

    return r.getTableId();
  }

  /** Inserts a row in the newly created table for the authenticated user. */
  private static void insertData(String tableId) throws IOException {
    Sql sql = fusiontables.query().sql("INSERT INTO " + tableId + " (Text,Number,Location,Address,Date) "
        + "VALUES (" + "'Google Inc', " + "1, " + "'22.816694,70.850418',  " + "'1600 Amphitheatre Parkway Mountain View, "
        + "CA 94043, USA','" + new DateTime(new Date()) + "')");

    try {
      sql.execute();
    } catch (IllegalArgumentException e) {
      // For google-api-services-fusiontables-v1-rev1-1.7.2-beta this exception will always
      // been thrown.
      // Please see issue 545: JSON response could not be deserialized to Sqlresponse.class
      // http://code.google.com/p/google-api-java-client/issues/detail?id=545
      e.printStackTrace();
    }
  }

  /** Deletes a table for the authenticated user. */
  private static void deleteTable(String tableId) throws IOException {
    View.header("Delete Sample Table");
    // Deletes a table
    Delete delete = fusiontables.table().delete(tableId);
    delete.execute();
  }
}

* * Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.services.samples.fusiontables.cmdline; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.util.DateTime; import com.google.api.services.drive.Drive; import com.google.api.services.drive.DriveScopes; import com.google.api.services.drive.Drive.Permissions; import com.google.api.services.drive.model.Permission; import com.google.api.services.fusiontables.Fusiontables; import com.google.api.services.fusiontables.Fusiontables.Query.Sql; import com.google.api.services.fusiontables.Fusiontables.Table.Delete; import com.google.api.services.fusiontables.FusiontablesScopes; import com.google.api.services.fusiontables.model.Column; import com.google.api.services.fusiontables.model.Sqlresponse; import com.google.api.services.fusiontables.model.Table; import com.google.api.services.fusiontables.model.TableList; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.UUID; /** * @author Christian Junk * */ public class FusionTablesSample { /** E-mail address of the service account. */ private static final String SERVICE_ACCOUNT_EMAIL = "XXXXXXXXXXXXXX@developer.gserviceaccount.com"; /** Global instance of the HTTP transport. */ private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport(); /** Global instance of the JSON factory. */ private static final JsonFactory JSON_FACTORY = new JacksonFactory(); private static Fusiontables fusiontables; /** Authorizes the installed application to access user's protected data. */ private static Credential authorizeNew() throws Exception { // Build service account credential. GoogleCredential credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT) .setJsonFactory(JSON_FACTORY) .setServiceAccountId(SERVICE_ACCOUNT_EMAIL) .setServiceAccountScopes(FusiontablesScopes.FUSIONTABLES) .setServiceAccountPrivateKeyFromP12File(new File("key.p12")) .build(); return credential; } /** Authorizes the installed application to access user's protected data. */ private static Credential authorizeNewDrive() throws Exception { GoogleCredential credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT) .setJsonFactory(JSON_FACTORY) .setServiceAccountId(SERVICE_ACCOUNT_EMAIL) .setServiceAccountScopes(DriveScopes.DRIVE) .setServiceAccountPrivateKeyFromP12File(new File("key.p12")) .build(); return credential; } /** * Insert a new permission. * * @param service Drive API service instance. * @param fileId ID of the file to insert permission for. * @param value User or group e-mail address, domain name or {@code null} "default" type. * @param type The value "user", "group", "domain" or "default". * @param role The value "owner", "writer" or "reader". * @return The inserted permission if successful, {@code null} otherwise. */ private static Permission insertPermission(Drive service, String fileId, String value, String type, String role) { Permission newPermission = new Permission(); newPermission.setValue(value); newPermission.setType(type); newPermission.setRole(role); try { System.out.println("service"+service.permissions()); return service.permissions().insert(fileId, newPermission).execute(); } catch (IOException e) { System.out.println("An error occurred: " + e); } return null; } /** Global Drive API client. */ private static Drive drive; public static void main(String[] args) { try { try { // System.out.println(System.getProperty("user.home")); // authorization Credential credential = authorizeNew(); Credential credential1 = authorizeNewDrive(); // set up global FusionTables instance fusiontables = new Fusiontables.Builder( HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName( "FusionTable").build(); // set up the global Drive instance drive = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential1).setApplicationName( "FusionTable").build(); System.out.println(drive.files().list()); Permissions perms=drive.permissions(); System.out.println(perms); // run commands // listTables(); ArrayList<String> list=listTables(""); // String tableId = createTable(); // insertData(tableId); for(String tableid:list) { insertPermission(drive, tableid, "XXXXXXXXX@gmail.com","anyone","owner"); // System.out.print(" permission for table id is " + perms.list(tableid)); showRows(tableid); // deleteTable(tableid); } listTables(); // deleteTable(tableId); // success! return; } catch (IOException e) { System.err.println(e.getMessage()); } } catch (Throwable t) { t.printStackTrace(); } System.exit(1); } /** * @param tableId * @throws IOException */ private static void showRows(String tableId) throws IOException { View.header("Start Showing Rows From Table"); Sql sql = fusiontables.query().sql("SELECT Text,Number,Location,Address,Date FROM " + tableId); try { Sqlresponse response= sql.execute(); System.out.println( response.getColumns()); System.out.println( response.getRows()); } catch (IllegalArgumentException e) { // For google-api-services-fusiontables-v1-rev1-1.7.2-beta this exception will always // been thrown. // Please see issue 545: JSON response could not be deserialized to Sqlresponse.class // http://code.google.com/p/google-api-java-client/issues/detail?id=545 } View.header("End Showing Rows From Table"); } /** List tables for the authenticated user. */ private static void listTables() throws IOException { View.header("Listing My Tables"); // Fetch the table list Fusiontables.Table.List listTables = fusiontables.table().list(); TableList tablelist = listTables.execute(); if (tablelist.getItems() == null || tablelist.getItems().isEmpty()) { System.out.println("No tables found!"); return; } for (Table table : tablelist.getItems()) { View.show(table); View.separator(); } } private static ArrayList<String> listTables(String a) throws IOException { View.header("Listing My Tables"); ArrayList<String> rt=new ArrayList<String>(); // Fetch the table list Fusiontables.Table.List listTables = fusiontables.table().list(); TableList tablelist = listTables.execute(); if (tablelist.getItems() == null || tablelist.getItems().isEmpty()) { System.out.println("No tables found!"); return rt; } for (Table table : tablelist.getItems()) { rt.add(table.getTableId()); View.show(table); View.separator(); } return rt; } /** Create a table for the authenticated user. */ private static String createTable() throws IOException { View.header("Create Sample Table"); // Create a new table Table table = new Table(); table.setName(UUID.randomUUID().toString()); table.setIsExportable(true); table.setDescription("Sample Table"); // Set columns for new table table.setColumns(Arrays.asList(new Column().setName("Text").setType("STRING"), new Column().setName("Number").setType("NUMBER"), new Column().setName("Location").setType("LOCATION"), new Column().setName("Address").setType("STRING"), new Column().setName("Date").setType("DATETIME"))); // Adds a new column to the table. Fusiontables.Table.Insert t = fusiontables.table().insert(table); Table r = t.execute(); View.show(r); return r.getTableId(); } /** Inserts a row in the newly created table for the authenticated user. */ private static void insertData(String tableId) throws IOException { Sql sql = fusiontables.query().sql("INSERT INTO " + tableId + " (Text,Number,Location,Address,Date) " + "VALUES (" + "'Google Inc', " + "1, " + "'22.816694,70.850418', " + "'1600 Amphitheatre Parkway Mountain View, " + "CA 94043, USA','" + new DateTime(new Date()) + "')"); try { sql.execute(); } catch (IllegalArgumentException e) { // For google-api-services-fusiontables-v1-rev1-1.7.2-beta this exception will always // been thrown. // Please see issue 545: JSON response could not be deserialized to Sqlresponse.class // http://code.google.com/p/google-api-java-client/issues/detail?id=545 e.printStackTrace(); } } /** Deletes a table for the authenticated user. */ private static void deleteTable(String tableId) throws IOException { View.header("Delete Sample Table"); // Deletes a table Delete delete = fusiontables.table().delete(tableId); delete.execute(); } }

2 个答案:

答案 0 :(得分:0)

Java对我来说很有意义......发布通用FT Java模块有什么意义? 我在这里看不到任何Google地图代码,甚至没有看到您尝试访问的表格ID。 使用UI访问您的表:

https://www.google.com/fusiontables/DataSource?docid= [编码表ID]

在“共享”设置中,选择“在网络上公开”或“有链接的任何人”。现在可以通过Google Maps javascript API访问它。

答案 1 :(得分:0)

  

我在stackoverflow中读到了一些他们谈到过FT的问题(我甚至无法做到这一点)

您的代码已包含该代码。看看你的insertPermission()方法。复制粘贴的奇迹...... :)

根据Google地图文档,您只能在地图上显示共享为&#34; public&#34;或者&#34;未上市&#34;。 资料来源:https://developers.google.com/maps/documentation/javascript/layers#FusionTablesSetup

要实现这一点,请在角色&#34;读者&#34;并键入&#34;任何人&#34;。有关更多信息和Java示例,请参阅:https://developers.google.com/drive/v2/reference/permissions/insert