Ruby on Rails实习生求助:如何让页面加载时自动触发定位功能?
实现页面加载自动获取位置的修改方案
嘿,我懂你要的效果啦!既然你已经搞定了点击按钮获取位置的功能,改成页面加载自动执行其实超简单,咱们直接调整代码逻辑就行:
核心修改思路
原来的代码是把地理定位逻辑绑定在#current-location按钮的点击事件上,现在只需要把这部分逻辑直接移到页面加载完成的回调函数里,不需要再依赖按钮点击触发。
修改后的完整代码
function geolocationSuccess(position) { var latitude = position.coords.latitude; var longitude = position.coords.longitude; var geocoder = new google.maps.Geocoder(); var latlng = {lat: latitude, lng: longitude}; geocoder.geocode({'location': latlng}, function(results, status) { if (status === google.maps.GeocoderStatus.OK) { if (results[0]){ var user_address = results[0].formatted_address; document.getElementById("current_location").innerHTML = user_address; }else { console.log('No results found for these coords.'); } }else { console.log('Geocoder failed due to: ' + status); } }); } function geolocationError() { console.log("please enable location for this feature to work!"); } $(document).on("ready page:ready", function() { // 直接在这里执行地理定位逻辑,不需要绑定点击事件 if ("geolocation" in navigator) { navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError); } else { alert("Geolocation not supported!"); } });
关键修改点说明
- 移除了原本绑定按钮点击的
$("#current-location").on("click", ...)代码块 - 把按钮点击事件里的地理定位判断逻辑,直接放到了
ready page:ready的回调函数中,适配Rails Turbo/Turbolinks的页面切换场景 - 页面加载完成后会自动触发位置获取请求,浏览器会弹出位置权限请求弹窗(这是安全机制,用户授权后才能获取位置信息)
内容的提问来源于stack exchange,提问作者Edi Junior
相关产品推荐
相关产品推荐

