2017-07-07 36 views
0

它曾經在我的代碼中工作過,但是最近的變化讓我看起來被打破了。我嘗試在網上尋找解決方案,但是這對我來說似乎是特定於我所需要的。我想要的只是一個「alert();」以顯示瀏覽器地理位置服務請求是否被拒絕。以下是未加入警報的代碼。謝謝。如何在地理位置服務被拒絕時添加警報?

 if (navigator.geolocation) { 
      // Locate position 
      navigator.geolocation.getCurrentPosition(displayPosition); 
     } else { 
      alert('It seems like Geolocation, which is required for this page, is not enabled in your browser. Please use a browser which supports it.'); 
     } 
     blacklisted_areas = { 
      'area 51': [1, 2], 
      'pink unicorn zoo': [1, 2], 
     }; 
     // Success callback function 
     function displayPosition(pos) { 
    var mylat = pos.coords.latitude; 
    var mylong = pos.coords.longitude; 
    var thediv = document.getElementById('locationinfo'); 
    thediv.innerHTML = '<p>Your longitude is :' + mylong + ' and your latitide is ' + mylat + '</p>'; 

    var blacklisted = false; 
    for (let x of Object.values(blacklisted_areas)) { 
    if (mylat === x[0] && mylong === x[1]) { 
     blacklisted = true; 
    } 
    } 
    if(!blacklisted){ 
    window.location="insertURLHere"; 
    } 


} 

回答

1

只是處理錯誤案例:

navigator.geolocation.getCurrentPosition(displayPosition, onError); 
function onError (error) { 
    if (error.code == error.PERMISSION_DENIED) 
     alert("you denied geolocation"); 
}; 
1

傳遞一個回調的錯誤。

if (navigator.geolocation) { 
    // Get user's geo position. 
    navigator.geolocation.getCurrentPosition(function success(position) { 
    // Success 
    }, function error(err) { 
    // Geolcoation denied. 
    if (err.code === err.PERMISSION_DENIED) { 
     // Determine reason for error. 
     if (err.message.match(/secure/i)) { 
     console.alert('INSECURE_ORIGIN'); 
     } else { 
     console.alert('INSECURE_ORIGIN'); 
     } 
    } 
    }); 
}