0

我正在关注这个教程 - https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple

我已经输入了代码<?php echo the_field('post_code'); ?>,但我想在加载时对其进行地理编码,而不是通过输入和提交。我怎样才能做到这一点?

这就是我所拥有的:

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
    <script>
var geocoder;
var map;
function initialize() {
  geocoder = new google.maps.Geocoder();
  var latlng = new google.maps.LatLng(52.375599, -3.471680);
  var mapOptions = {
    zoom: 8,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}

function codeAddress() {
  var address = '<?php echo the_field('post_code'); ?>';
  geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location
      });
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
}

google.maps.event.addDomListener(window, 'load', initialize);

    </script>
<div id="map-canvas" style="float:left;height:250px; width:625px;margin-top:25px;"></div>
4

2 回答 2

1
function initialize() {
  geocoder = new google.maps.Geocoder();
  var latlng = new google.maps.LatLng(52.375599, -3.471680);
  var mapOptions = {
    zoom: 8,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

  codeAddress(); // This should do it. Assuming all the code is working.
}
于 2013-05-30T09:56:32.740 回答
0

调用传递地址作为参数codeAddress()initialize()

function initialize() {
  geocoder = new google.maps.Geocoder();
  var latlng = new google.maps.LatLng(52.375599, -3.471680);
  var mapOptions = {
    zoom: 8,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  codeAddress(address);
}
于 2013-05-30T09:56:58.007 回答