Google Maps JS API地理位置权限被拒绝

时间:2015-04-24 16:02:00

标签: google-maps-api-3

我正在使用Geolocation功能尝试通过HTML5查找用户的设备,如下所示: https://developers.google.com/maps/documentation/javascript/examples/map-geolocation

如果用户接受提示,一切都很有效,但如果用户拒绝权限,我想提供一组备用的LatLng坐标。目前(包括上面链接的Google示例),如果用户拒绝权限,则会呈现地图所在的空白区域。

因此,如果用户接受,将地图渲染到其所在位置,并且如果用户拒绝权限,则渲染地图以替代地理位置为中心。

// Note: This example requires that you consent to location sharing when
// prompted by your browser. If you see a blank space instead of the map, this
// is probably because you have denied permission for location sharing.

var map;

function initialize() {
  var mapOptions = {
    zoom: 6
  };
  map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);

  // Try HTML5 geolocation
  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: 'Location found using HTML5.'
      });

      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);

0 个答案:

没有答案