2017-02-03 43 views
0

我一直在學習由Nikil Abraham編碼爲傻瓜編碼。 在這本書中有一個項目,其中包含的代碼用於開發一個餐廳的應用程序,在點擊登記按鈕時,餐廳的優惠券在餐廳步行5至10分鐘內向客戶發送警報。警報問題 - 使用Harvesine距離公式的地理位置公式

我輸入了所有使用html,css和javascript通過codepen的代碼,並且由於某種原因警報不會彈出。

我研究了哪裏可能會出錯,但我真的被卡住了。

下面是代碼:

在HTML:

<head> 
<title>McDuck's App</title> 
</head> 
<body> 
<h1>McDuck's Local Offers</h1> 

<button onclick="getLocation()">CheckIn</button> 

<div id="geodisplay"/> 
<div id="effect"/> 


</body> 

的CSS:

body { 
text-align: center; 
background: white; 
} 

h1, h2, h3, p { 
font-family: Sans-Serif; 
color: black; 
} 

p { 
font-size: 1em; 
} 

的JavaScript:

function getLocation() { 
if (navigator.geolocation){ 
navigator.geolocation.getCurrentPosition(showLocation); 
} 
} 

//商店位置

function showLocation(position){ 
var mcduckslat=53.510207; 
var mcduckslon=-6.399289; 

//當前位置

var currentpositionlat=position.coords.latitude; 
var currentpositionlon=position.coords.longitude; 

//計算當前的位置和McDuck的位置之間的距離

var distance=getDistanceFromLatLonInMiles(mcduckslat, mcduckslon,  
currentpositionlat, currentpositionlon); 

//displays the locaton using .inner.HTML property and the lat & long  
coordinates from your current location 

document.getElementById("geodisplay").inner.HTML="Latitude: " +  
currentpositionlat + "<br>Longitude: " + currentpositionlon; 

} 

//haversine distance formula 

    function getDistanceFromLatLonInKm(lat1, lon1, lat2, lon2) { 
    var R = 6371; //Radius of earth in km 
    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 * 0.372823; //Distance in miles           
return d; 
} 

function deg2rad(deg) { 
    return deg * (Math.PI/180); 
} 

alert(distance); 

if (distance < 0.5) { 
alert("You get a free meal"); 
} 
else { 
alert("Thanks for checking in!"); 
} 

鏈接到copepen http://codepen.io/Saharalara/pen/Grxmmj

+0

我的回答對你有幫助嗎?點擊我答案頂部的鏈接查看解決方案的工作情況。 – taylorsabell

回答

0

TL; DR:這是看到它工作的小提琴荷蘭國際集團:https://jsfiddle.net/pnruje2g/6/


與此擺弄了一會兒後,我發現4點的問題。

第一個是在Chrome瀏覽器的非HTTPS環境(如CodePen)中棄用getCurrentPosition()。

這裏有確切消息我在谷歌瀏覽器獲得:

getCurrentPosition()和watchPosition()在不安全 起源不再起作用。要使用此功能,您應該考慮將您的 應用程序切換到安全來源,例如HTTPS。有關更多詳細信息,請參閱 https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins

如果您使用的是Google Chrome瀏覽器,則可能需要在其他瀏覽器中試用此功能。它確實在本地網站上工作。

下一個問題是調用不存在的函數getDistanceFromLatLonInMiles()。我通過致電getDistanceFromLatLonInKm()取代了它。

第三個問題是試圖分配一個不存在的屬性,您引用inner.HTML而不是innerHTML

第四個問題是警報的位置。目前他們只是坐在你的JS文件的底部,沒有做任何事情。我們希望在完成計算後顯示警報。我將您的提醒移至showLocation()函數的末尾。

這聽起來像是你正在進入軟件開發,所以絕對不會感到所有這些問題不知所措。隨着時間的推移,它會變得更容易。

讓我知道這是否有幫助。

+0

它的工作!非常感謝你的幫助。真的幫助我瞭解更多。我有一種感覺,英里有一個問題。再次感謝,真的很感激它! – Sarah