我正在尝试在this google dev.guide之后对place_id进行反向地址解析(Google)。但是,我想在加载页面时执行地理编码功能,而不是使用“ 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程序员的建议都将受到欢迎!

最佳答案

我收到您的代码Uncaught ReferenceError: ChIJw2IskpfGxUcRRNxZ4A_lGWk is not defined的javascript错误。 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>

关于javascript - 页面加载时如何初始化反向地址解析?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36719302/

10-09 09:37