尝试更改位置以使用 Google 街景静态 API 捕获静态图像

Trying to get location change to capture a static image with Google Street View Static API

我正在尝试使用 Ionic2 构建一个应用程序,允许用户通过 Google 街景静态 API 加载 StreetViewPanorama 对象。加载视图后,用户应该能够以他们选择的任何方式操纵街景(离开原始位置、缩放等)。完成此任务后,用户将捕获最终街景的静态图像。

当我尝试拍摄新街景位置的照片时,我遇到了困难。我正在尝试使用 Google 的 documentation on static image generation to achieve this。不幸的是,在创建对象后,我无法引用 Panorama 对象的属性。我对 Javascript 比较陌生,所以请多多包涵。

为了生成街景全景图,我运行以下函数(从底部initMap()开始):

 /**
  * Creates the map options for panorama generation. This includes adjusting the coordinate
  * position of a user to the nearest available street view. Following creation of the settings,
  * it generates the street view on a user's device.
  *
  * @param userLocation a JSON object whose keys are 'lat' and 'lng' and whose values are
  *                     the corresponding latitude and longitude respectively
  */
  generatePanorama(userLocation): void {
    var streetviewService = new google.maps.StreetViewService;
    streetviewService.getPanorama({
      location: userLocation,
      preference: google.maps.StreetViewPreference.NEAREST,
      radius: 100},
      function(result, status) {
        console.log("Adjusted latitude: ", result.location.latLng.lat(),
                    "\nAdjusted longitude: ", result.location.latLng.lng());
        new google.maps.StreetViewPanorama(document.getElementById('street-view'), {
          position: result.location.latLng,
          pov: {heading: 165, pitch: 0},
          zoom: 1
        });
      });
  }


  /**
  * Uses a device's native geolocation capabilities to get the user's current position
  *
  * @return a JSON object whose keys are 'lat' and 'lng' and whose calues are the corresponding
  *         latitude and longitude respectively
  */
  getLocation(callback): void {
    Geolocation.getCurrentPosition().then((position) => {
      console.log("Latitude: ", position.coords.latitude, "\nLongitude: ", position.coords.longitude);
      callback({lat: position.coords.latitude, lng: position.coords.longitude});
    }).catch((error) => {
      console.log('Error getting location', error);
    });
  }

 /**
  * Initialize a Google Street View Panorama image
  */
  initMap(): void {
    this.getLocation(this.generatePanorama);
  }

我正在创建全景图,如上所示,代码如下,

new google.maps.StreetViewPanorama(document.getElementById('street-view'), {
      position: result.location.latLng,
      pov: {heading: 165, pitch: 0},
      zoom: 1
    });

我无法将此对象分配给实例变量以用于以下两个函数:

 /**
  * Generates a URL to query the Google Maps API for a static image of a location
  *
  * @param lat the latitude of the static image to query
  * @param lng the longitude of the static image to query
  * @param heading indicates the compass heading of the camera
  * @param pitch specifies the up or down angle of the camera relative to the street
  * @return a string that is the URL of a statically generated image of a location
  */
  generateStaticMapsURL(lat, lng, heading, pitch): string {
    var url = "https://maps.googleapis.com/maps/api/streetview?size=600x300&location=";
    url += lat + "," + lng;
    url += "&heading=" + heading;
    url += "&pitch=" + pitch;
    url += "&key=SECRET_KEY";
    return url;
  }

  openShareModal() {
    console.log("Final Latitude: ", this.panorama.getPosition().lat());
    console.log("Final Longitude: ", this.panorama.getPosition().lng());
    console.log("Final Heading:", this.panorama.getPov().heading);
    console.log("Final Heading:", this.panorama.getPov().pitch);
    let myModal = this.modalCtrl.create(ShareModalPage);
    myModal.present();
  }

当我尝试直接或通过辅助函数将对象分配给实例变量时,我得到一个 UnhandledPromiseRejectionWarning 但没有任何效果。那么,如何在创建街景对象后从中提取位置、航向和间距等信息呢?

感谢您的帮助!

更新 1: 该程序目前构建良好。我分配了一个 panorama: any; 的实例变量,然后继续尝试使用以下函数和赋值更新该变量。

/**
  * Creates the map options for panorama generation. This includes adjusting the coordinate
  * position of a user to the nearest available street view. Following creation of the settings,
  * it generates the street view on a user's device.
  *
  * @param userLocation a JSON object whose keys are 'lat' and 'lng' and whose values are
  *                     the corresponding latitude and longitude respectively
  */
  generatePanorama(userLocation): void {
    var streetviewService = new google.maps.StreetViewService;
    streetviewService.getPanorama({
      location: userLocation,
      preference: google.maps.StreetViewPreference.NEAREST,
      radius: 100},
      function(result, status) {
        console.log("Adjusted latitude: ", result.location.latLng.lat(),
                    "\nAdjusted longitude: ", result.location.latLng.lng());
        this.panorama = new google.maps.StreetViewPanorama(document.getElementById('street-view'), {
          position: result.location.latLng,
          pov: {heading: 165, pitch: 0},
          zoom: 1
        });
      });
  }

当我这样做然后尝试在另一个函数中使用 panorama 变量时,它似乎认为 panorama 是一个空变量。此外,全景地图根本无法加载!这是我尝试在其中使用全景变量的第二个函数。

openShareModal() {
    console.log("Final Latitude: ", this.panorama.getPosition().lat());
    console.log("Final Longitude: ", this.panorama.getPosition().lng());
    console.log("Final Heading:", this.panorama.getPov().heading);
    console.log("Final Heading:", this.panorama.getPov().pitch);
    let myModal = this.modalCtrl.create(ShareModalPage);
    myModal.present();
  }

更新 2: 发布我的全部代码以寻求帮助。

import { Component, ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams, ViewController, ModalController } from 'ionic-angular';
import { ShareModalPage } from '../share-modal/share-modal';
import { Geolocation } from 'ionic-native';
declare var google;

/**
 * Generated class for the StreetViewModalPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-street-view-modal',
  templateUrl: 'street-view-modal.html',
})

export class StreetViewModalPage {

  @ViewChild('map') mapElement;
  map: any;
  panorama: any;

  constructor(public navCtrl: NavController, public navParams: NavParams,
              public viewCtrl: ViewController, public modalCtrl: ModalController) {}

  ionViewDidLoad() {
    console.log('ionViewDidLoad StreetViewModalPage');
    this.initMap();
  }
  

  /**
  * Creates the map options for panorama generation. This includes adjusting the coordinate
  * position of a user to the nearest available street view. Following creation of the settings,
  * it generates the street view on a user's device.
  *
  * @param userLocation a JSON object whose keys are 'lat' and 'lng' and whose values are
  *                     the corresponding latitude and longitude respectively
  */
  generatePanorama(userLocation): void {
    var streetviewService = new google.maps.StreetViewService;
    streetviewService.getPanorama({
      location: userLocation,
      preference: google.maps.StreetViewPreference.NEAREST,
      radius: 100},
      function(result, status) {
        console.log("Adjusted latitude: ", result.location.latLng.lat(),
                    "\nAdjusted longitude: ", result.location.latLng.lng());
        this.panorama = new google.maps.StreetViewPanorama(document.getElementById('street-view'), {
          position: result.location.latLng,
          pov: {heading: 165, pitch: 0},
          zoom: 1
        });
      });
  }


  /**
  * Uses a device's native geolocation capabilities to get the user's current position
  *
  * @return a JSON object whose keys are 'lat' and 'lng' and whose calues are the corresponding
  *         latitude and longitude respectively
  */
  getLocation(callback): void {
    Geolocation.getCurrentPosition().then((position) => {
      console.log("Latitude: ", position.coords.latitude, "\nLongitude: ", position.coords.longitude);
      callback({lat: position.coords.latitude, lng: position.coords.longitude});
    }).catch((error) => {
      console.log('Error getting location', error);
    });
  }

  /**
  * Initialize a Google Street View Panorama image
  */
  initMap(): void {
    this.getLocation(this.generatePanorama);
  }

  /**
  * Generates a URL to query the Google Maps API for a static image of a location
  *
  * @param lat the latitude of the static image to query
  * @param lng the longitude of the static image to query
  * @param heading indicates the compass heading of the camera
  * @param pitch specifies the up or down angle of the camera relative to the street
  * @return a string that is the URL of a statically generated image of a location
  */
  generateStaticMapsURL(lat, lng, heading, pitch): string {
    var url = "https://maps.googleapis.com/maps/api/streetview?size=600x300&location=";
    url += lat + "," + lng;
    url += "&heading=" + heading;
    url += "&pitch=" + pitch;
    url += "&key=XXXXXXXXXXXX"; // TODO : Make private
    return url;
  }

  openShareModal() {
    console.log("Final Latitude: ", this.panorama.getPosition().lat());
    console.log("Final Longitude: ", this.panorama.getPosition().lng());
    console.log("Final Heading:", this.panorama.getPov().heading);
    console.log("Final Heading:", this.panorama.getPov().pitch);
    let myModal = this.modalCtrl.create(ShareModalPage);
    myModal.present();
  }

}

而对应的HTML...

<ion-content>
   <div #map id="street-view" style="height:100%; width:100%;"></div>
   <button ion-button style="position: absolute; top: 5px; right: 5px; z-index: 1;" (click)="openShareModal()" large><ion-icon name="camera"></ion-icon></button>
</ion-content>

我认为 this.panorama 为空的原因是您创建它的范围。

我在 phone 所以我不能真正输入代码,但是尝试在 generatePanorama 上添加 const self = this; 就在方法的开头和分配 this.panorama 请替换为 self.panorama = ....

如果可行,请告诉我。我会尽快试用,看看是否满足您的需求。

这就是我要说的

/**
  * Creates the map options for panorama generation. This includes adjusting the coordinate
  * position of a user to the nearest available street view. Following creation of the settings,
  * it generates the street view on a user's device.
  *
  * @param userLocation a JSON object whose keys are 'lat' and 'lng' and whose values are
  *                     the corresponding latitude and longitude respectively
  */
  generatePanorama(userLocation): void {
    var self = this;
    var streetviewService = new google.maps.StreetViewService;
    streetviewService.getPanorama({
      location: userLocation,
      preference: google.maps.StreetViewPreference.NEAREST,
      radius: 100},
      function(result, status) {
        console.log("Adjusted latitude: ", result.location.latLng.lat(),
                    "\nAdjusted longitude: ", result.location.latLng.lng());
        self.panorama = new google.maps.StreetViewPanorama(document.getElementById('street-view'), {
          position: result.location.latLng,
          pov: {heading: 165, pitch: 0},
          zoom: 1
        });
      });
  }

更新 - 工作示例

class StackTest {
 constructor() {
    this.initMap();
    // This next line is very important to keep the scope.
    this.openShareModal = this.openShareModal.bind(this);
    // This next line should be defined by ionic itself so it won't be needed
    document.getElementById('open').addEventListener('click', this.openShareModal);
  }
  
  generatePanorama(userLocation) {
    var self = this;
    var streetviewService = new google.maps.StreetViewService;
    streetviewService.getPanorama({
      location: userLocation,
      preference: google.maps.StreetViewPreference.NEAREST,
      radius: 100},
      function(result, status) {
        console.log("Adjusted latitude: ", result.location.latLng.lat(),
                    "\nAdjusted longitude: ", result.location.latLng.lng());
        self.panorama = new google.maps.StreetViewPanorama(document.getElementById('pano'), {
          position: result.location.latLng,
          pov: {heading: 165, pitch: 0},
          zoom: 1
        });
        self.bindEvents();
      });
  }
  
  bindEvents() {
   var self = this;
    this.panorama.addListener('pano_changed', function() {
        var panoCell = document.getElementById('pano-cell');
        panoCell.innerHTML = self.panorama.getPano();
    });

    this.panorama.addListener('links_changed', function() {
        var linksTable = document.getElementById('links_table');
        while (linksTable.hasChildNodes()) {
          linksTable.removeChild(linksTable.lastChild);
        }
        var links = self.panorama.getLinks();
        for (var i in links) {
          var row = document.createElement('tr');
          linksTable.appendChild(row);
          var labelCell = document.createElement('td');
          labelCell.innerHTML = '<b>Link: ' + i + '</b>';
          var valueCell = document.createElement('td');
          valueCell.innerHTML = links[i].description;
          linksTable.appendChild(labelCell);
          linksTable.appendChild(valueCell);
        }
    });

    this.panorama.addListener('position_changed', function() {
        var positionCell = document.getElementById('position-cell');
        positionCell.firstChild.nodeValue = self.panorama.getPosition() + '';
    });

    this.panorama.addListener('pov_changed', function() {
        var headingCell = document.getElementById('heading-cell');
        var pitchCell = document.getElementById('pitch-cell');
        headingCell.firstChild.nodeValue = self.panorama.getPov().heading + '';
        pitchCell.firstChild.nodeValue = self.panorama.getPov().pitch + '';
    });
  }

  getLocation(callback) {
   callback({lat: 37.869, lng: -122.255});
  }

  initMap() {
    this.getLocation(this.generatePanorama.bind(this));
  }

  openShareModal() {
    console.log("Final Latitude: ", this.panorama.getPosition().lat());
    console.log("Final Longitude: ", this.panorama.getPosition().lng());
    console.log("Final Heading:", this.panorama.getPov().heading);
    console.log("Final Heading:", this.panorama.getPov().pitch);
    alert('If you see this alert this.panorama was defined :)');
    /* let myModal = this.modalCtrl.create(ShareModalPage); */
    /* myModal.present() */;
  }
}

function instantiateTheClass() {
 new StackTest();
}
/* Always set the map height explicitly to define the size of the div
 * element that contains the map. */
#map {
  height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}
#open {
  position: absolute;
  top: 0;
  right: 0;
}
#floating-panel {
  position: absolute;
  top: 10px;
  left: 25%;
  z-index: 5;
  background-color: #fff;
  padding: 5px;
  border: 1px solid #999;
  text-align: center;
  font-family: 'Roboto','sans-serif';
  line-height: 30px;
  padding-left: 10px;
}
#pano {
  width: 50%;
  height: 100%;
  float: left;
}
#floating-panel {
  width: 45%;
  height: 100%;
  float: right;
  text-align: left;
  overflow: auto;
  position: static;
  border: 0px solid #999;
}
<div id="pano"></div>
<button id="open">Open modal</button>
<div id="floating-panel">
<table>
  <tr>
    <td><b>Position</b></td><td id="position-cell">&nbsp;</td>
  </tr>
  <tr>
    <td><b>POV Heading</b></td><td id="heading-cell">270</td>
  </tr>
  <tr>
    <td><b>POV Pitch</b></td><td id="pitch-cell">0.0</td>
  </tr>
  <tr>
    <td><b>Pano ID</b></td><td id="pano-cell">&nbsp;</td>
  </tr>
  <table id="links_table"></table>
</table>
</div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAH1G2yf7g4br8sQehvB7C1IfBh8EIaAVE&callback=instantiateTheClass">
</script>