在iframe中加载HTML5地理位置时访问用户的纬度和经度 [英] Accessing user's latitude and longitude when loading HTML5 geolocation in iframe
问题描述
我正在使用HTML5 Geolocation来获取用户的经纬度。当页面直接打开时,它适用于所有浏览器,但现在我必须将地理位置代码放在iframe中。将其放入iframe后,地理位置不会提示用户的坐标。
I am using HTML5 Geolocation to get the user's latitude and longitude. It works fine on all browsers when the page is opened directly, but now I have to put the geolocation code inside an iframe. After putting it in the iframe, the geolocation doesn't prompt for the user's coordinates.
如何在iframe中加载页面时获取用户的经纬度?
How do I get the user's latitude and longitude when the page is loading in an iframe?
让我们说这是代码:
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to get your coordinates:</p>
<button onclick="getLocation()">Try It</button>
<script>
var x=document.getElementById("demo");
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else{x.innerHTML="Geolocation is not supported by this browser.";}
}
function showPosition(position)
{
x.innerHTML="Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
</body>
</html>
推荐答案
你可能已经解决了这个问题,但是,问题在于:
You probably have solved this already, but nonetheless, the issue lies here:
var x = document.getElementById(demo);
var x = document.getElementById("demo");
上面按原样运行页面时很好,但是当通过iframe加载时,文档指的是父框架(不是你关心的孩子)。尝试这样的事情:
The above is fine when you run the page as-is, but when loaded via an iframe, the "document" refers to the parent frame (not the child you care about). Try something like this:
var x = document.getElementById(frameId)。contentWindow.document.getElementById(demo);
var x = document.getElementById("frameId").contentWindow.document.getElementById("demo");
其中frameId是指包含显示纬度/经度信息的页面的框架。
where "frameId" refers to the frame that houses the page displaying the lat / long info.
对使用有一些限制,有关更多信息,请参阅此优秀帖子:如何从iframe内部选择元素
There are some restrictions on usage, for more info see this excellent thread: How to pick element from inside iframe
这篇关于在iframe中加载HTML5地理位置时访问用户的纬度和经度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!