当用户拒绝共享位置时,Google地图不会初始化

时间:2016-04-06 17:17:47

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

以下是使用地图的页面的演示链接: http://cdn.moranautoads.com/hrad/locate-a-dealer

如果用户拒绝分享其位置,我的Google地图将不会初始化。我确实有一个条件,检查好像

if ( navigator.geolocation ){
  navigator.geolocation.getCurrentPosition( UserLocation, errorCallback,{maximumAge:60000,timeout:10000});
}
else{
  ClosestLocation( 29.6116451, -90.7522943 );
}

然而,似乎没有得到承认。我在else部门尝试了一个警报,但没有任何结果。

我能够记录错误"User denied geolocation prompt",但这并没有帮助我发现我的问题。

我感谢任何帮助。这是整个代码:

var map;    // Google map object

// Initialize and display a google map
function Init() {
  // HTML5/W3C Geolocation
  if ( navigator.geolocation ) {
    navigator.geolocation.getCurrentPosition( UserLocation, errorCallback,{maximumAge:60000,timeout:10000});
  }
  // Default to Washington, DC
  else {
    alert( "You didn't share your location." );
    ClosestLocation( 29.6116451, -90.7522943 );
  }
}

function errorCallback( error ) {
  console.log( error );
}

// Callback function for asynchronous call to HTML5 geolocation
function UserLocation( position ) {
  ClosestLocation( position.coords.latitude, position.coords.longitude );
}

// Display a map centered at the nearest location with a marker and InfoWindow.
function ClosestLocation( lat, lon ){
    // Create a Google coordinate object for where to center the map
    var latlng = new google.maps.LatLng( lat, lon );

    // Map options for how to display the Google map
    var mapOptions = { zoom: 7, center: latlng, styles:styles, disableDefaultUI: true };

    // Show the Google map in the div with the attribute id 'map-canvas'.
    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    // find the closest location to the user's location
    var closest = 0;
    var mindist = 99999;

    var marker, i;
    var infowindow = new google.maps.InfoWindow();

    for(var i = 0; i < dealers.length; i++){

                    // place markers(custom img) in provided location
        marker = new google.maps.Marker({
          position: new google.maps.LatLng(dealers[i].lat, dealers[i].lon),
          icon: dealers[i].img,
          map: map
        });

        google.maps.event.addListener(marker, 'click', (function(marker, i) {
          return function() {
            infowindow.setContent(dealers[i].dealerInfo);
            infowindow.open(map, marker);
          }
        })(marker, i));

        // get the distance between user's location and this point
        var dist = Haversine( dealers[i].lat, dealers[i].lon, lat, lon );

        // check if this is the shortest distance so far
        if ( dist < mindist )
        {
            closest = i;
            mindist = dist;
        }
    }

    // Create a Google coordinate object for the closest location
    var latlng = new google.maps.LatLng( dealers[closest].lat, dealers[closest].lon );

    map.setCenter( latlng );
    infowindow.setContent(dealers[closest].dealerInfo);
    infowindow.open(map, new google.maps.Marker({
      position: latlng,
      map: map
    }));
}

// Convert Degress to Radians
function Deg2Rad( deg ) {
   return deg * Math.PI / 180;
}

// Get Distance between two lat/lng points using the Haversine function
// First published by Roger Sinnott in Sky & Telescope magazine in 1984 (“Virtues of the Haversine”)
//
function Haversine( lat1, lon1, lat2, lon2 )
{
    var R = 6372.8; // Earth Radius in Kilometers

    var dLat = Deg2Rad(lat2-lat1);
    var dLon = Deg2Rad(lon2-lon1);

    var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(Deg2Rad(lat1)) * Math.cos(Deg2Rad(lat2)) * Math.sin(dLon/2) * Math.sin(dLon/2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    var d = R * c;

    // Return Distance in Kilometers
    return d;
}

// Call the method 'Init()' to display the google map when the web page is displayed ( load event )
google.maps.event.addDomListener( window, 'load', Init );

1 个答案:

答案 0 :(得分:1)

有时会出现地理定位服务,但在用户拒绝分享时不会调用错误功能。最简单的解决方案,始终在ClosestLocation函数中调用Init,如果成功,则让地理位置重置位置。

proof of concept fiddle

代码段

var map; // Google map object

// Initialize and display a google map
function Init() {
  ClosestLocation(29.6116451, -90.7522943);
  // HTML5/W3C Geolocation
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(UserLocation, errorCallback, {
      maximumAge: 60000,
      timeout: 10000
    });
  }
  // Default to Washington, DC
  else {
    alert("You didn't share your location.");
    ClosestLocation(29.6116451, -90.7522943);
  }
}

function errorCallback(error) {
  console.log(error);
}

// Callback function for asynchronous call to HTML5 geolocation
function UserLocation(position) {
  ClosestLocation(position.coords.latitude, position.coords.longitude);
}

// Display a map centered at the nearest location with a marker and InfoWindow.
function ClosestLocation(lat, lon) {
  // Create a Google coordinate object for where to center the map
  var latlng = new google.maps.LatLng(lat, lon);

  // Map options for how to display the Google map
  var mapOptions = {
    zoom: 7,
    center: latlng,
    /* styles:styles, */
    disableDefaultUI: true
  };

  // Show the Google map in the div with the attribute id 'map-canvas'.
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

  // find the closest location to the user's location
  var closest = 0;
  var mindist = 99999;

  var marker, i;
  var infowindow = new google.maps.InfoWindow();

  for (var i = 0; i < dealers.length; i++) {

    // place markers(custom img) in provided location
    marker = new google.maps.Marker({
      position: new google.maps.LatLng(dealers[i].lat, dealers[i].lon),
      icon: dealers[i].img,
      map: map
    });

    google.maps.event.addListener(marker, 'click', (function(marker, i) {
      return function() {
        infowindow.setContent(dealers[i].dealerInfo);
        infowindow.open(map, marker);
      }
    })(marker, i));

    // get the distance between user's location and this point
    var dist = Haversine(dealers[i].lat, dealers[i].lon, lat, lon);

    // check if this is the shortest distance so far
    if (dist < mindist) {
      closest = i;
      mindist = dist;
    }
  }

  // Create a Google coordinate object for the closest location
  var latlng = new google.maps.LatLng(dealers[closest].lat, dealers[closest].lon);

  map.setCenter(latlng);
  infowindow.setContent(dealers[closest].dealerInfo);
  infowindow.open(map, new google.maps.Marker({
    position: latlng,
    map: map
  }));
}

// Convert Degress to Radians
function Deg2Rad(deg) {
  return deg * Math.PI / 180;
}

// Get Distance between two lat/lng points using the Haversine function
// First published by Roger Sinnott in Sky & Telescope magazine in 1984 (“Virtues of the Haversine”)
//
function Haversine(lat1, lon1, lat2, lon2) {
  var R = 6372.8; // Earth Radius in Kilometers

  var dLat = Deg2Rad(lat2 - lat1);
  var dLon = Deg2Rad(lon2 - lon1);

  var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(Deg2Rad(lat1)) * Math.cos(Deg2Rad(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  var d = R * c;

  // Return Distance in Kilometers
  return d;
}

// Call the method 'Init()' to display the google map when the web page is displayed ( load event )
google.maps.event.addDomListener(window, 'load', Init);

var dealers = [{
  lat: 30.2240897,
  lon: -92.0198427,
  img: "http://maps.google.com/mapfiles/ms/micons/blue.png",
  dealerInfo: "something"
}, {
  lat: 29.9510658,
  lon: -90.0715323,
  img: "http://maps.google.com/mapfiles/ms/micons/yellow.png",
  dealerInfo: "another thing"
}];
html,
body,
#map-canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas"></div>