[英]how to get the current location of the user along with latitude and longitude in OpenLayers
[英]How to get longitude and latitude of my current location and display on two separate HTML form
任何人都可以通过单击按钮来帮助获取我当前的经度和纬度,并在 HTML 中的两个单独的输入表单上显示。 下面是我的表单的样子,点击“获取”按钮,它将获得我当前的 LNG 和 LAT,然后显示在 forms 1 和 2 上。
<form>
<button onclick="onFormSubmit()">GET CURRENT LOCATION</button>
<script>
function onGeoSuccess (position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
// NEXT 2 LINES WILL SET VALUE OF RESPECTIVE INPUTS
document.getElementById('lat').value = lat;
document.getElementById('lng').value = long;
// MAKE API CALL HERE, OR ANY OTHER NEXT STEPS
}
function onGeoError (err) {
console.error("Error while trying to get position", err);
}
function onFormSubmit () {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(onGeoSuccess, onGeoError);
} else {
alert('GeoLocation not supported or not allowed');
}
}</script>
<div class="form-group">
<input type="text" name="lat" class="form-control" id="lat" placeholder="Your Latitude" data-msg="Please enter your latitude">
<div class="validate"></div>
</div>
<div class="form-group">
<input type="text" name="lng" class="form-control" id="lng" placeholder="Your Longitude" data-msg="Please enter your Longitude">
<div class="validate"></div>
</div>
<div class="form-group">
<input type="text" name="subject" class="form-control" id="contact-subject" placeholder="Subject" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject">
<div class="validate"></div>
</div>
</form>
这可以使用一些简单的 JavaScript 来完成:
/* Add an onsubmit method to your form */
<form onsubmit="onFormSubmit()">
/*...*/
function onGeoSuccess (position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
// NEXT 2 LINES WILL SET VALUE OF RESPECTIVE INPUTS
document.getElementById('lat').value = lat;
document.getElementById('lng').value = long;
// MAKE API CALL HERE, OR ANY OTHER NEXT STEPS
}
function onGeoError (err) {
console.error("Error while trying to get position", err);
}
function onFormSubmit () {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(onGeoSuccess, onGeoError);
} else {
alert('GeoLocation not supported or not allowed');
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.