我有一个简单的地图,只要它们允许 HTML5 地理位置,它就应该以用户的位置为中心加载。如果他们不选择让我们看到他们的位置,则有一个功能,但由于某种原因它不起作用。
这是代码:
var x = document.getElementById("msg");
function getLocation() {
if (Modernizr.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
}
else { x.innerHTML = "Geolocation is not supported by this browser."; }
}
function showPosition(position) {
var mapOptions = {
center: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("Map"), mapOptions);
var acOptions = {
types: ['establishment']
};
var autocomplete = new google.maps.places.Autocomplete(document.getElementById('autocomplete'), acOptions);
autocomplete.bindTo('bounds', map);
var infoWindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map
});
google.maps.event.addListener(autocomplete, 'place_changed', function () {
infoWindow.close();
var place = autocomplete.getPlace();
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
marker.setPosition(place.geometry.location);
infoWindow.setContent('<div><strong>' + place.name + '</strong><br />');
infoWindow.open(map, marker);
google.maps.event.addListener(marker, 'click', function (e) {
infoWindow.open(map, marker);
});
});
}
function showError(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
default:
x.innerHTML = "An unknown error occurred."
break;
}
}
google.maps.event.addDomListener(window, 'load', getLocation);
当然,一个<p>
元素在正文中,其 id 为 msg。