javascript - 如何打印 HTML 地理位置?
问题描述
我正在使用 HTML5 Geolocation 并希望在输入字段中打印返回的用户位置。
这可能吗?如果有怎么办?
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;
}
<input type="text">
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
解决方案
I have edited the answer. the problem in your code was that the variable x was coming null since you were trying to do getElemntById for the p tag not defined in the code yet.so I have put the HTML part above the javascript code.
<input type="text">
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<script>
var x = document.getElementById("demo");
console.log(x);
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>
推荐阅读
- javascript - React Native 读取 yaml 文件
- django - django 无法显示搜索结果
- mysql - mySQL 查询:查找包含关键字的内容以及具有该关键字的对象的数量
- angular - 如何更新特定用户的按钮点击记录?
- python - 如何从字典的键中计算对象?
- python - 了解 netlib fftpack 的结果
- react-native - 反应本机地图动态位置导致未安装组件上的反应状态更新
- python - 广度优先搜索 Python 代码到深度优先搜索
- excel - 用户表单按钮不调用模块上的代码
- asp.net - 如何使用 AngularJS 使用 ASP.Net 通用处理程序文件插入数据(文件和文本)?