【问题标题】:How to initialize reverse geocode upon page load?如何在页面加载时初始化反向地理编码?
【发布时间】:2016-04-19 13:03:51
【问题描述】:

我正在尝试对 place_id 执行反向地理编码 (Google),遵循 this google dev.guide。但是,我想在加载页面时执行地理编码功能,而不是初始化地理编码功能的“点击”事件。所以我用这个代码替换了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 google-maps geocoding reverse-geocoding


    【解决方案1】:

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

    这个:

    var placeId = ChIJw2IskpfGxUcRRNxZ4A_lGWk;
    

    应该是:

    var placeId = "ChIJw2IskpfGxUcRRNxZ4A_lGWk";
    

    代码 sn-p:

    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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-14
      • 1970-01-01
      相关资源
      最近更新 更多