Google方向服务。如何检测浏览器中是否禁用了地理位置

时间:2012-02-03 09:49:15

标签: google-maps google-maps-api-3

如果用户已禁用了位置功能,或者他使用了非地理位置支持的功能。

如何以编程方式执行此操作?这将被执行,如果我在我的浏览器中启用地理位置,如果我不启用,我想要一些其他代码来执行。我把其他代码将在我不启用或使用不支持的浏览器时执行。

<script type="text/javascript">
  var directionDisplay;
  var directionsService = new google.maps.DirectionsService();
  var map;

  function initialize() {
    directionsDisplay = new google.maps.DirectionsRenderer();
    var chicago = new google.maps.LatLng(41.850033, -87.6500523);
    var myOptions = {
      zoom:7,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      center: chicago
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    directionsDisplay.setMap(map);
  }

  function calcRoute() {
    var start = document.getElementById("start").value;
    var end = document.getElementById("end").value;
    var request = {
        origin:start, 
        destination:end,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
      }
    });
  }
</script>
</head>
<body onload="initialize()">
<div>

1 个答案:

答案 0 :(得分:1)

我会使用modernizer来嗅出浏览器是否支持地理位置,然后采取适当的措施。

if (Modernizr.geolocation) {
  //do geolocation/gmaps stuff
} else {
  //do something else
} 

您甚至可以加载填充程序,为不支持它的浏览器提供地理定位功能。 modernizer documentation section中有一些示例。

e.g。

Modernizr.load({
  test: Modernizr.geolocation,
  yep : 'geo.js',
  nope: 'geo-polyfill.js'
});

- 编辑

<html>
<head>
<script type="text/javascript"  src="modernizer.js"></script>
<script type="text/javascript"
  src="http://maps.googleapis.com/maps/api/js?key=&sensor=true"></script>
<script>

var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;

function initialize() { 

  if (Modernizr.geolocation) {
  // Do the geolocation  
      navigator.geolocation.getCurrentPosition(initializeGeo, handle_error);          
  } else {
  // No geolocation path
  initializeNonGeo();
  } 
}

function handle_error(err) {
  alert("Geolocation could not be run");
  if (err.code == 1) {
    alert("user denied");// user said no!
  }
  initializeNonGeo();
}

function initializeGeo() {
  alert("has geolocation");
  directionsDisplay = new google.maps.DirectionsRenderer();
  var chicago = new google.maps.LatLng(41.850033, -87.6500523);
  var myOptions = {
    zoom:7,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: chicago
  }
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  directionsDisplay.setMap(map);
} 

function initializeNonGeo() {
   alert("no geolocation"); //do non geo stuff.
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width: 500px; height: 300px"></div>

</body>
</html>