1

我遇到了一个问题,如果禁用地理定位,那么地图应该以指定位置为中心,但禁用时没有加载任何内容。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也不提醒。

4

1 回答 1

1

至少在 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!");
}

在我的浏览器上,如果我单击“拒绝”按钮,则会提示“真实”,然后是“失败”。如果您想提供相同的行为,无论地理定位失败还是用户拒绝它,我建议使用如下代码:

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();
}
于 2013-02-11T02:38:26.753 回答