我正在尝试创建一个对谷歌地图进行地理编码的表单。我有来自地图 API 的基本代码,但它只适用于一个字段:“地址”。
我没有使用“getElementByID”,而是使用“getElementByClassName”,以便它可以使用我设置的任何字段中的数据。
也就是说,它不起作用。通过使用类而不是 ID,我是否朝着正确的方向前进?
下面是我正在使用的代码。API-KEY 省略。
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% }
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=mykey=false">
</script>
<script type="text/javascript">
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(39.861933, -83.067746);
var mapOptions = {
zoom: 3,
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;
address += " "+document.getElementById('street_add').value;
address += " "+document.getElementById('city').value;
address += " "+document.getElementById('state').value;
address += " "+document.getElementById('postcode').value;
address += " "+document.getElementById('country').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">
<form action="" name="" method="post">
<input id="address" type="hidden" value="">
<input id="street_add" type="textbox" value="" class="address">
<input id="city" type="textbox" value="" class="address">
<input id="state" type="textbox" value="" class="address">
<input id="postcode" type="textbox" value="" class="address">
<input id="country" type="textbox" value="" class="address">
<input type="button" value="Geocode" onclick="codeAddress()">
</form>
</div>
<div id="map-canvas" style="height:40%;top:30px;"></div>
</body>
</html>