我使用第三个API来定位用户的当前位置,然后将latlng提供给initMap函数,但除了地图应该是灰色屏幕之外什么也没有显示。我还检查了控制台的错误,但没有。 Console.log还返回其中包含正确值的latlng对象。这是代码:
<script>
var mapDiv = document.getElementById('map');
var pos;
$.get( "http://ip-api.com/json", function(data) {
pos = new google.maps.LatLng(data.lat, data.lon);
});
function initMap() {
var map = new google.maps.Map(mapDiv, {
zoom: 14,
center: pos,
mapTypeControl: false
});
var marker = new google.maps.Marker({
position: pos,
map: map,
draggable: false,
animation: google.maps.Animation.DROP,
title: 'Gotcha!'
});
marker.setMap(map);
}
</script>
答案 0 :(得分:2)
试试此代码
<script type="text/javascript">
window.onload = function (){
var mapDiv = document.getElementById('map');
var pos;
$.get( "http://ip-api.com/json", function(data) {
pos = new google.maps.LatLng(data.lat, data.lon);
initMap();
});
function initMap() {
var map = new google.maps.Map(mapDiv, {
zoom: 10,
center: pos
});
var marker = new google.maps.Marker({
position: pos,
map: map,
draggable: false,
animation: google.maps.Animation.DROP,
title: 'Gotcha!'
});
}
}
</script>