当地理定位被禁用时,谷歌地图不以位置为中心



我遇到了一个问题,如果地理定位被禁用,那么地图应该以指定的位置为中心,但当它被禁用时,没有加载任何内容。当启用地理定位时,if语句的第一部分工作正常。为什么else零件在禁用时不能工作?

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(function (position) { 
    var latitude = position.coords.latitude;                    
    var longitude = position.coords.longitude;               
    var coords = new google.maps.LatLng(latitude, longitude);
    var directionsService = new google.maps.DirectionsService();
    var directionsDisplay = new google.maps.DirectionsRenderer();
    var mapOptions = 
    {
      zoom: 15,  
      center: coords, 
      mapTypeControl: true, 
      navigationControlOptions:
      {
        style: google.maps.NavigationControlStyle.SMALL 
      },
      mapTypeId: google.maps.MapTypeId.ROADMAP 
    };
    map = new google.maps.Map(document.getElementById("mapContainer"), mapOptions);
    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById(''));
    var request = {
      origin: coords,
      destination: 'BT42 1FL',
      travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    directionsService.route(request, function (response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
      }
    });
  });
}
else {
  alert("Geolocation API is not supported in your browser.");
  var mapOptions =
  {
    zoom: 15,  
    center: 'BT42 1FL',
    mapTypeControl: true, 
    navigationControlOptions:
    {
      style: google.maps.NavigationControlStyle.SMALL 
    },
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById("mapContainer"), mapOptions);
}

alert也不报警。

至少在Chrome 24中,当用户拒绝地理定位时,navigator.geolocation不是错误的。

如果用户拒绝地理定位,将调用失败回调(getCurrentPosition的第二个参数)。当然,对于任何其他无法获取位置的情况,也会发生这种情况。播放以下代码(可在jsfiddle中获得):

function success() {
    alert("success!");
}
function failure() {
    alert("failure!");
}
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(success, failure);
    alert("truthy!");
} else {
  alert("falsy!");
}

在我的浏览器上,如果我点击"拒绝"按钮,就会发出"truthy"one_answers"failure"的警报。如果你想给出相同的行为,无论地理定位失败还是用户拒绝,我建议代码如下:

function noGeoInfo() {
    alert("couldn't get your location info; making my best guess!");
}
function geoInfo(position) {
    alert("hey your position is " + position + " isn't that swell?");
}
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(geoInfo, noGeoInfo);
} else {
    noGeoInfo();
}

最新更新