我使用了第三个API来定位用户的当前位置,然后将latlng提供给initMap函数,但除了地图应该在的灰色屏幕外,什么也没有显示。我还检查了控制台的错误,但没有。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>
试试这个代码
<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>