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

时间:2016-04-19 13:03:52

标签: javascript google-maps geocoding reverse-geocoding

我试图在this google dev.guide之后在place_id上​​执行反向地理编码(Google)。但不是点击'要初始化地理编码功能的事件,我想在加载页面时执行地理编码功能。所以我用这段代码替换了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程序员的任何建议都会非常受欢迎!

1 个答案:

答案 0 :(得分:1)

我的代码出现了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>