我正在学习谷歌地图API,我正在尝试在地图上找到当前位置以及标记。 Marker工作正常但当前位置部分无法正常工作。我的代码附在下面。请告诉我我错在哪里。
<script>
var map;
var myCenter = new google.maps.LatLng(13.0827, 80.2707)
var map;
function initialize() {
var myLatlng = myCenter;
var mapOptions = {
zoom: 4,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
draggable: true
});
// To add the marker to the map, call setMap();
marker.setMap(map);
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Great! your location is found.'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
答案 0 :(得分:0)
如果您在浏览器控制台中签入,则会显示错误,因为未在handleNoGeolocation()函数中定义map变量
您可以使用在Initialize()和handleNoGeolocation()函数之外定义的map变量。
更新了JS代码:
var map;
var myCenter = new google.maps.LatLng(13.0827, 80.2707)
function initialize() {
var myLatlng = myCenter;
var mapOptions = {
zoom: 4,
center: myLatlng
}
// No declaration of local map variable here
map = new google.maps.Map(document.getElementById('map'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
draggable: true
});
// To add the marker to the map, call setMap();
marker.setMap(map);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Great! your location is found.'
});
map.setCenter(pos);
}, function () {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);