如何直接在代码中输入街道地址

时间:2013-03-19 05:41:40

标签: google-maps-api-3 geocoding

我想使用google map api v3,例如本例https://google-developers.appspot.com/maps/documentation/javascript/examples/geocoding-simple

但没有此输入字段

<div>
  <input id="address" type="textbox" value="Sydney, NSW">
  <input type="button" value="Geocode" onclick="codeAddress()">
</div>

我想直接在代码中指定街道地址,例如“75 wall st,new york”。我该怎么做呢?以下是该示例网址的代码。任何人都知道需要删除/添加什么?

<link href="https://google-developers.appspot.com/maps/documentation/javascript/examples/default.css" rel="stylesheet">
<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(-34.397, 150.644);
    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 = 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);
      }
    });
  }
</script>
</head>
<body onload="initialize()">
<div>
<input id="address" type="textbox" value="Sydney, NSW">
<input type="button" value="Geocode" onclick="codeAddress()">
</div>
<div id="map-canvas" style="height:90%;top:30px"></div>

1 个答案:

答案 0 :(得分:0)

我想你可以更新函数来执行此操作:

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);
  }
});

}

一旦您想要更新地图,只需致电:

codeAddress('75 wall st, new york');

如果您正在使用jQuery,可以将其放入文档就绪函数或代码的其他部分。