用于确定是否启用地理位置的功能

时间:2013-04-10 18:42:54

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

我有一个功能可以确定用户是否启用了地理位置,如果用户启用了地理位置,则会显示Google地图,如果不是,则会显示不同的地图。

function init_maps() {
  if (navigator.geolocation) { 
    navigator.geolocation.getCurrentPosition(geoInfo, noGeoInfo, { timeout: 20000 });
  } else {
    noGeoInfo();
  }

  function geoInfo(position) { 
    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);
      var request = {
        origin: coords, //start point for directions
        destination: '54.861283, -6.326805', //end point for directions
        travelMode: google.maps.DirectionsTravelMode.DRIVING 
      };
      directionsService.route(request, function (response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
          directionsDisplay.setDirections(response);
        }
      });
    });
    //}

    function noGeoInfo() { 
      var location = new google.maps.LatLng(54.861283, -6.326805); 
      var mapOptions = { 
        center: location, 
        zoom: 15, 
        mapTypeId: google.maps.MapTypeId.ROADMAP 
      };
      var map = new google.maps.Map(document.getElementById("mapContainer"), mapOptions);
      marker = new google.maps.Marker({  
        position: location, 
        map: map 
      });
    }
  }
}

当用户点击链接时,会调用函数init_maps()。问题是当页面加载时,div中没有显示任何内容,如果我删除:

  if (navigator.geolocation) { 
    navigator.geolocation.getCurrentPosition(geoInfo, noGeoInfo, { timeout: 20000 });
  } else {
    noGeoInfo();
  }

  function geoInfo(position) {

然后按预期加载地图。如果我有if else来确定是否启用了地理位置,为什么不显示它?

0 个答案:

没有答案