如何在页面加载时初始化反向地理编码?

How to initialize reverse geocode upon page load?

我正尝试在 place_id 上执行反向地理编码 (Google),然后是 this google dev.guide。但是我不想使用 'click' 事件来初始化地理编码功能,而是想在加载页面时执行地理编码功能。所以我用这段代码替换了 click-eventListener:

        document.addEventListener("DOMContentLoaded", function() {
        geocodePlaceId(geocoder, map, infowindow);
        });

在地理编码函数中,我硬编码了 place_id(通过示例):

function geocodePlaceId(geocoder, map, infowindow) {
        var placeId = ChIJw2IskpfGxUcRRNxZ4A_lGWk;
        geocoder.geocode({'placeId': placeId}, function(results, status) {
          if (status === google.maps.GeocoderStatus.OK) {
            etcetc
      }

不幸的是,这不起作用,即没有初始化反向地理编码。非常欢迎向这位非常温和的 java 程序员提出任何建议!

你的代码出现 javascript 个错误:Uncaught ReferenceError: ChIJw2IskpfGxUcRRNxZ4A_lGWk is not defined。 placeId 是一个字符串。

这个:

var placeId = ChIJw2IskpfGxUcRRNxZ4A_lGWk;

应该是:

var placeId = "ChIJw2IskpfGxUcRRNxZ4A_lGWk";

代码片段:

function geocodePlaceId(geocoder, map, infowindow) {
  var placeId = "ChIJw2IskpfGxUcRRNxZ4A_lGWk";
  geocoder.geocode({
    'placeId': placeId
  }, function(results, status) {

    if (status === google.maps.GeocoderStatus.OK) {
      map.setZoom(11);
      map.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({
        position: results[0].geometry.location,
        map: map
      });
      infowindow.setContent(results[0].formatted_address);
      infowindow.open(map, marker);
    } else {
      window.alert('Geocoder failed due to: ' + status);
    }
  });
}

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  var geocoder = new google.maps.Geocoder();
  var infowindow = new google.maps.InfoWindow();
  geocodePlaceId(geocoder, map, infowindow);
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>