我正在尝试创建一个可以对Google地图进行地理编码的表单。我有map API的基本代码,但它只适用于一个字段:'address'。
我没有使用'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>
答案 0 :(得分:0)
地理编码器采用表示地址的单个字符串。您当前没有创建它,您传递的是未定义的值(没有getElementByClassName,它是getElementsByClassName并返回一个HTML元素数组)
将单独的值组合成一个字符串:
var 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;