[英]how to get the current location of the user along with latitude and longitude in OpenLayers
[英]How to get current location (latitude and longitude) and send it to an reverse geocoding API?
我正在尝试获取当前的纬度和经度,并将其传递给名为OpenCage Geocoder API的Web API。 这是我所做的:
// reverse geocoding
function geocode() {
let lat,long;
window.onload = function() {
var startPos;
var geoSuccess = function(position) {
startPos = position;
lat = startPos.coords.latitude;
long = startPos.coords.longitude;
};
navigator.geolocation.getCurrentPosition(geoSuccess);
};
geoResponse = function(reponse)
{
document.getElementById("address").innerHTML = response.results[17].toString();
};
let script = document.createElement('script');
script.src = "https://api.opencagedata.com/geocode/v1/json?q="+ lat +","+ long +"&key=00f711f73483427c8577e646aa2bf4bf&jsonp=geoResponse";
document.body.appendChild(script);
}
我是编码的新手,但我有点卡住了。 有没有更简单的方法来调用此特定的API,我很迷路。 任何帮助将非常感谢!
我已修改并附加了您的代码段以供参考! 在您的getResponse中,您收到了作为响应的参数,并在代码中调用了response.results [17] .toString(),该参数未定义!
window.onload = function() { navigator.geolocation.getCurrentPosition(function (position) { var lat = position.coords.latitude; var long = position.coords.longitude; var script = document.createElement('script'); script.src = "https://api.opencagedata.com/geocode/v1/json?q="+ lat +","+ long +"&key=00f711f73483427c8577e646aa2bf4bf&jsonp=geoResponse"; document.body.appendChild(script); }); } geoResponse = function(reponse){ document.getElementById("address").innerHTML = reponse.results[0].formatted; }
<div id="address"> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.