gpt4 book ai didi

javascript - 将谷歌地图设置为在加载时对邮政编码进行地理编码

转载 作者:行者123 更新时间:2023-11-29 17:16:01 25 4
gpt4 key购买 nike

我使用 Google Maps API 显示基于邮政编码的 map ,然后使用 Google 的地理编码服务 ( https://google-developers.appspot.com/maps/documentation/javascript/examples/geocoding-simple ) 将邮政编码转换为纬度和经度并显示 map 。

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>

最佳答案

只需从 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();
}

关于javascript - 将谷歌地图设置为在加载时对邮政编码进行地理编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17725403/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com