输入地址时自动显示街景地图

时间:2018-03-29 13:52:54

标签: google-maps

我想放入一个街道地址,并以编程方式确定坐标和航向,以生成街景地图。 instantstreetview.com这样做,所以我知道可以做到。来自文档:

function initialize() {
  var fenway = {lat: 42.345573, lng: -71.098326};
  var map = new google.maps.Map(document.getElementById('map'), {
    center: fenway,
    zoom: 14
  });
  var panorama = new google.maps.StreetViewPanorama(
      document.getElementById('pano'), {
        position: fenway,
        pov: {
          heading: 34,
          pitch: 10
        }
      });
  map.setStreetView(panorama);
}

问题是,我不知道我想要的地址的标题。有没有一种简单的方法来实现这一目标?

1 个答案:

答案 0 :(得分:1)

您可能希望从LatLng呈现的StreetViewLocation获取StreetViewPanorama,以使用computeHeading()中的Geometry library来计算标题Javascript API。

看看this sample JSBin。我创建了两个街景视图div,其中两个地址的lat / lng彼此相对。请注意,无论lat / lng如何,都返回相同的pano,但没有标题信息,因此视图是相同的:

Two addresses one view

现在,看看这个this modified JSBin。在根据全景的StreetViewLocation.latLng和传递到StreetViewService的地址的lat / lng计算标题并将其用作全景图的pov后,会显示每个标题的正确街景图像地址:

two addresses two views

相关代码:

var ll = new google.maps.LatLng(37.435292,-122.129517);
var svs = new google.maps.StreetViewService();

svs.getPanorama({location: ll, preference: 'nearest'}, function(data, status){
        var pos = data.location.latLng;
        var head = google.maps.geometry.spherical.computeHeading(pos, ll);
        var panorama = new google.maps.StreetViewPanorama(
        document.getElementById('street-view'),
        {
          pano: data.location.pano,
          pov: {heading: head, pitch:0}
        });
     });

编辑:添加another simple JSBin,显示使用Geocoder获取地址的LatLng:相关代码:

var ll;
var geocoder = new google.maps.Geocoder();
var svs = new google.maps.StreetViewService();

geocoder.geocode({address: "757 Moreno Ave Palo Alto, CA"}, function(results, status) {
  if (status == 'OK') {
    ll = results[0].geometry.location;
    svs.getPanorama({location: ll, preference: 'nearest'}, function(data, status){
      var pos = data.location.latLng;    
      var head = google.maps.geometry.spherical.computeHeading(pos, ll);
      panorama = new google.maps.StreetViewPanorama(
      document.getElementById('street-view'),
      {
        pano: data.location.pano,
        pov: {heading: head, pitch:0}
      });
    });
  }
});
相关问题