页面加载时的Google地理编码,而不是通过输入

时间:2013-05-30 09:33:46

标签: php javascript google-maps-api-3

我正在关注此课程 - 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>

2 个答案:

答案 0 :(得分: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.
}

答案 1 :(得分: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);
}