当单击POI时,在谷歌地图上获取placeId。

3
我正在我的网站上使用Google Maps JS V3 API。当用户搜索地点时,我能够通过placeId使用getDetails。我希望当用户点击POI时也能做到这一点。但是,我似乎找不到在用户点击POI时获取此placeId的方法,而不是使用搜索框。

我已经进行了几天的研究,但没有找到任何接近的东西。

我看到了这个功能请求,我想知道是否真的没有办法通过POI点击获取placeId: https://code.google.com/p/gmaps-api-issues/issues/detail?id=8113&q=poi&colspec=ID%20Type%20Status%20Introduced%20Fixed%20Summary%20Stars%20ApiType%20Internal

非常感谢您的帮助!

2个回答

4
谷歌没有提供任何文档化的API方法来通过点击POI获取地点ID。但是,我可以使用反向地理编码来获取地点ID。
首先,我们可以使用在这个Stack Overflow答案中描述的方法来获取POI的坐标。
其次,您可以使用getPosition()方法返回的坐标调用geocode方法以检索地址组件和地点ID。
这里有一个可工作的JS Fiddle

function initialize() {
  var mapOptions = {
    zoom: 14,
    center: new google.maps.LatLng(38.8862447, -77.02158380000003),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById('map_canvas'),
    mapOptions);

  geocoder = new google.maps.Geocoder;

  //keep a reference to the original setPosition-function
  var fx = google.maps.InfoWindow.prototype.setPosition;

  //override the built-in setPosition-method
  google.maps.InfoWindow.prototype.setPosition = function() {

    //this property isn't documented, but as it seems
    //it's only defined for InfoWindows opened on POI's
    if (this.logAsInternal) {
      google.maps.event.addListenerOnce(this, 'map_changed', function() {
        var map = this.getMap();

        //the infoWindow will be opened, usually after a click on a POI
        if (map) {

          //trigger the click
          google.maps.event.trigger(map, 'click', {
            latLng: this.getPosition()
          });
        }
      });
    }
    //call the original setPosition-method
    fx.apply(this, arguments);
  };

  google.maps.event.addListener(map, 'click', function(e) {
    //alert('clicked @' + e.latLng.toString())
    geocoder.geocode({
      'location': e.latLng
    }, function(results, status) {
      if (status === google.maps.GeocoderStatus.OK) {
        if (results[0]) {

          alert('place id: ' + results[0].place_id);


        } else {
          console.log('No results found');
        }
      } else {
        console.log('Geocoder failed due to: ' + status);
      }
    });

  });
}

google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_canvas {
  margin: 0;
  height: 100%;
}
<div id="map_canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js?callback=initialize" async defer></script>


他们确实这样做。有关更多详细信息,请参阅Mihail Shishkov的帖子。 - Dan H

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接