硬编码邮政地址以用于地理编码

时间:2014-01-08 12:16:17

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

我一直在Google地图开发网站上查看地理编码的示例。我找到了这个例子,并希望作为实验硬编码邮政编码,而不是使用输入框来获取地址(总体目标是让xml将邮政地址放在这里)。这只是对“地址”标签内的邮政地址进行硬编码的情况吗?我确实试过这个,但没有快乐。希望有道理吗?

<script>
    var geocoder;
    var map;

    function initialize() {

        geocoder = new google.maps.Geocoder();
        var latlng = new google.maps.LatLng(-34.397, 150.644);

        var mapOptions = {
            zoom: 8,
            center: latlng
        }

        map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    }

    function codeAddress() {

        var address = document.getElementById('address').value;
        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>
</head>
<body>
    <div id="panel">
      <input id="address" type="textbox" value="Sydney, NSW">
      <input type="button" value="Geocode" onclick="codeAddress()">
    </div>
    <div id="map-canvas"></div>
</body>

https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple

1 个答案:

答案 0 :(得分:0)

如果我理解得很好,你可以尝试这样:

http://jsfiddle.net/7g7qG/

var geocoder;
var map;
function initialize() {
  geocoder = new google.maps.Geocoder();
  var latlng = new google.maps.LatLng(-34.397, 150.644);
  var mapOptions = {
    zoom: 8,
    center: latlng
  }
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  codeAddress('London')
}

function codeAddress(address) {
  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);