我使用Google Maps API根据邮政编码显示地图,然后使用Google的地理编码服务(https://google-developers.appspot.com/maps/documentation/javascript/examples/geocoding-simple)将邮政编码转换为纬度和经度并显示地图。
Google页面上的示例使用按钮激活地理编码功能,我已将该代码用作起点。但是,我不想要一个按钮,我想硬编码邮政编码(我将用以后从自定义元输入中取出的字符串替换它)。我如何调整此代码以获取我在地址变量中声明的邮政编码并在初始加载时加载,而不是单击按钮?
希望这是有道理的。
<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>
答案 0 :(得分:3)
只需从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();
}
答案 1 :(得分:1)
已经加载 eventListener
。
google.maps.event.addDomListener(window, 'load', 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();
}
检查此Fiddle
答案 2 :(得分:1)
您无法在初始化时执行此操作,因为地理编码是异步的,您当时不会进行本地化。但是,您可以在初始化后立即调用地理编码,并在地理定位完成后立即居中:
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();
}
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);
}
});
}
当然你可以看到一些延迟,如果这是问题,那么你可以: