我正在构建一个表单,并希望使用Google的Geolocation API自动将用户的坐标填入其中一个字段。我只使用一个输入,因为两个坐标一起返回。文本字段将是只读的,因此用户无法更改该值。到目前为止我的代码没有工作......有什么建议吗?
代码:
<input type="text" id="cor" readonly placeholder="coordinates">
<input class="ra26" type="button" value="View Coordinates" Onclick="getLocation()">
<script> var x = document.getElementById("cor");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Lat: " + position.coords.latitude +
"<br>Lon: " + position.coords.longitude;
}
function showError(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}
</script>
答案 0 :(得分:0)
输入字段没有innerHTML
属性。
将所有innerHTML
更改为value
,如下所示:
x.value= "Geolocation is not supported...";
供参考: http://www.w3schools.com/jsref/prop_text_value.asp
另一方面,你可以将它显示在div或p标签中,如下所示:<div id="cordiv"></div>
<script>
var x = document.getElementById("cordiv");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
// now x refer's to a div-element, so you can make use of the innerHTML-Property:
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
// ...rest of your code here
</script>
答案 1 :(得分:0)
if(typeof navigator.geolocation!='undefined')
2
showPosition(),showError()需要一个参数