我正在尝试创建一个 1 页地图生成器,他们在其中输入地址和邮政编码。
这部分有效
Geolocation API 然后进行反向查找以获取经度和纬度,并将其填充到 2 个隐藏的输入字段以供以后使用。
这部分不起作用
然后,我需要使用 Maps API 从隐藏的输入中获取经度和纬度值并生成地图,但是,变量为 NULL,因为它们设置在单击时激活的函数中。
我需要能够在设置值后触发地图生成器代码,或者最初从一组数字传递一组值,然后单击按钮使用隐藏值重新运行代码。
<script>
var apiKey='REMOVED FOR PRIVACY';
var longitude, latitude, map;
jQuery(document).ready(function( $ ) {
$('#find-address').click(function () {
var address = $('#address').val();
var postcode = $('#postcode').val();
var addressClean = address.replace(/\s+/g, '+');
var postcodeClean = postcode.replace(/\s+/g, '+');
var apiCall = 'https://maps.googleapis.com/maps/api/geocode/json?address='+addressClean+',+'+postcodeClean+'&key='+apiKey+'';
$.getJSON(apiCall,function (data, textStatus) {
longitude = data.results[0].geometry.location.lng;
latitude = data.results[0].geometry.location.lat;
document.getElementById("long").value = longitude;
document.getElementById("lat").value = latitude;
});
setTimeout(function(){
longitude = $("input#long").val();
latitude = $("input#lat").val();
if(longitude && latitude){
longitude = parseFloat(longitude);
latitude = parseFloat(latitude);
initMap(longitude,latitude);
}
}, 1000);
});
});
function initMap(longitude,latitude) {
var myLatlng = new google.maps.LatLng(latitude,longitude);
var mapOptions = {
zoom: 12,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById("map-embed-div"), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
draggable: true,
title: "Where's your garden?"
});
};
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=REMOVED_FOR_PRIVACY&callback=initMap" async defer></script>
我尝试在 setTimeout 函数中调用该函数并在函数回调中传递值,但这会返回 NULL。
在 timeout 函数中移动所有内容会引发未定义 initMap 的 promise 错误。
牧羊人nacy
相关分类