0

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

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可以确定是否启用了地理位置,为什么它不显示?

4

0 回答 0