我正在使用Google Maps API显示基于邮政编码的地图,然后使用Google的地理编码服务(https://google-developers.appspot.com/maps/documentation/javascript/examples/geocoding-simple)来转换邮政编码进入经纬度并显示地图。
Google页面上的示例使用一个按钮来激活地理编码功能,并且我已将该代码用作起点。但是,我不需要按钮,我想用硬编码邮政编码(以后我将用来自自定义元输入的字符串替换它)。我将如何调整此代码以采用我在address变量中声明的邮政编码,并在初始加载时加载它,而不是单击按钮时加载它?
希望这是有道理的。
<script src="http://maps.googleapis.com/maps/api/js?key=XXX&sensor=false" type="text/javascript"></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 = 'PO19 1DQ';
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>
<input type="button" value="Geocode" onclick="codeAddress()">
<div id="map-canvas" style="width:100%;height:300px;"></div>
只需从initialize()函数底部调用codeAddress即可,例如:
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);
codeAddress();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句