【发布时间】:2018-08-05 12:52:11
【问题描述】:
我正在尝试使用 Google Maps API 地理编码。完整的代码在下面,我第一次尝试时它就起作用了,但现在它没有显示地图,我不知道为什么。
我什至尝试添加“alert(data.status);”它返回“OK”状态。
当我检查时,控制台显示“纬度”未在此处定义:
var myLatLng = {lat: latitude, lng: longitude};
加载 DOM 时设置的变量“纬度”不应该延续到上面的那一行,还是我对变量范围做错了什么?
<style>
#map {
height:200px;
width: 200px;
}
</style>
<script>
$(function() {
var jsonLatLng ='https://maps.googleapis.com/maps/api/geocode/json?address=Indianapolis&sensor=false';
$.getJSON(jsonLatLng, function (data) {
if (data.status="OK") {
latitude = data.results[0].geometry.location.lat;
longitude = data.results[0].geometry.location.lng;
} else { //A default lat/long so SOMETHING shows
latitude = 38.99;
longitude = -74.80;
}
});
});
</script>
然后是这个:
<div id="map"></div>
<script>
function initMap() {
var myLatLng = {lat: latitude, lng: longitude};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: ''
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD98yPUHrWE8QZkSxWR1Fno3_yd70cPQbA&callback=initMap">
</script>
【问题讨论】:
-
你没有声明变量经纬度
-
您说
latitude是一个全局变量,但根据您发布的代码,它不是全局变量。
标签: javascript jquery google-maps-api-3 google-maps-markers